INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
$wpdb->update Issue Can anyone see what I have wrong here? $wpdb->update( $table, array( 'lat'=>$paper_lat, 'lon'=>$paper_lon ), array( 'id'=> $result=>id ), array( '%d', '%d' ), array('%d') ); This gives me a white screen. As far as I can tell I have the format correct according the the codex but it is giving me fits. I am sure that it is something simple but if someone would point it out to me I would greatly appreciate it.
array( 'id'=> $result=>id ), should be array( 'id'=> $result->id ), I suspect that's your white screen issue.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, database, wpdb" }
How should I troubleshoot a database serialization issue with a WordPress migration I'm migrating a WordPress site from one server to another, and the entire migration seems fine, except the sidebars aren't moving over properly. The obvious thing that comes to mind is a serialization issue with the MySQL migration, but I'm not making any changes to the database because the domain name isn't changing (or even the server paths for that matter). I'm literally just moving it from one box to another.
Rather than mess around trying to find the serialised data that got messed up, just use a tool to migrate environments and avoid messing up serialised data. WP Migrate DB is a good one that handles serialised data properly. The free version does a great job, as long as you don't have a huge database. The Pro version is the duck's nuts, well worth the money.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "mysql, migration" }
Display Images from Array with wp_get_attachment_image() I'd like the client to be able to type any image ID (number) from any gallery / attachment and then displaying it with wp_get_attachment_image(). Here is my code: if ( $images ) { foreach ( $images as $image ) { echo '<li>'; echo wp_get_attachment_image( $images, 'thumbnail' ); // notice this part echo '</li>'; } When I do print_r $images, I get this array: Array ( [0] => 318 [1] => 304 [2] => 301 [3] => 299 [4] => 297 ) and it works if I hardcoding the array, like echo wp_get_attachment_image( 304, 'thumbnail' );, but of course I'd like it to appear dynamically. How to do that? Thanks in advance.
check your code pass `$image` in `wp_get_attachment_image` not whole array `$images`. > Be careful when pass parameters if ( $images ) { foreach ( $images as $image ) { echo '<li>'; echo wp_get_attachment_image( $image, 'thumbnail' ); // notice this part echo '</li>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "images" }
Set start page depending on screen width I'm building a responsive theme and would like to have different start pages depending on screen width. In this case, the start page is set in WP admin and contains an image map built on a cunstom page template. On mobilde devices this image map doesn't work so well, so I'd like set one of the other pages as start page. I guess I can merge front-template with standard-template and somehow achieve this with media queries, but would prefer a javascrip/jQuery solution. Thanks
It's pretty hard for PHP to know your screen width. It's more of a job for jQuery. But your approach seems kind of backward. If the site is supposed to be responsive -- why are you trying to deliver _different_ pages to your visitors based on screen width? It would seem you should handle varying content via media queries. So if you have 5 pieces of content... let's say 1. Header A - intended for desktop 2. Header B - intended for mobile 3. Content - same for all 4. Footer A - intended for desktop 5. Footer B - intended for mobile You would **hide** the mobile (B) components when screen width is greater than X, and **show** the desktop (A) components. Conversely, when screen width is less than X, you would do the opposite: **showing** mobile components (B) and **hiding** desktop components (A). Make sense?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, jquery, javascript, responsive" }
Import JSON feed to Wordpress We have received a URL which is a JSON file apparently: I am completely clueless when it comes to JSON and Wordpress. Anybody know where to start? We will need to create individual posts from this JSON file I presume..
1. json_decode the JSON into an array. $slices = json_decode(file_get_contents('yourJSONFile.json'),true); 2. Loop into the data if ($slices) { foreach ($slices as $slice) { $title = $slice[1]; // insert more logic here } } 3. Create a post programmatically by using wp_insert_post. // Create post object $my_post = array( 'post_title' => $title, 'post_content' => 'This is my content', 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array(8,39) ); // Insert the post into the database and return the new post ID $post_id = wp_insert_post( $my_post, true ); if ( is_wp_error( $post_id ) ) { // error handling.... } More details in this tutorial: <
stackexchange-wordpress
{ "answer_score": 11, "question_score": 4, "tags": "json" }
count number of all comments by a user on different (non-repeated) posts I thank you in advance for your help. I am using Wordpress for about 2 years, but always avoiding SQL inside my scripts and looking for built-in functions to perform my goals. To count the comments submitted by a specific user with `$user->ID` as id, I didn't find a built-in way, so I am using: global $wpdb; $count = $wpdb->get_var( 'SELECT COUNT( comment_id ) FROM '. $wpdb->comments .' WHERE user_id = '.$user->ID.' AND comment_approved = "1" AND comment_type NOT IN ("pingback", "trackback" )' ); Actually my goal is to count number of all comments by a user on different posts. In other words, if a user commented 2 or more times on the same post, then only increment the `$count` variable by one . Your help is appreciated.
If you want to count the number of posts the user commented on, you can try: global $wpdb; $sql = 'SELECT COUNT( comment_ID ) FROM ' . $wpdb->comments . ' WHERE user_id = %d AND comment_approved = "1" AND comment_type NOT IN ("pingback", "trackback" ) GROUP by comment_post_ID'; $count = $wpdb->get_var( $wpdb->prepare( $sql, $user->ID ) ); where we group by the post ID.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments, sql" }
Displaying a custom field in Category Archives I am using WordPress 3.5.1 / Twenty Twelve Theme. I would like to display a custom field in my Category Archives. I have the following custom field working in my single.php , it displays a custom url / title <a href=" echo get_post_meta($post->ID, "user_submit_url", true); ?>" target="_blank"> <h1 class="entry-title"><?php the_title(); ?> </a> I would like to put the following code underneath the "entry-title" in Category Archives. I am confused of were to put the following php code, either in category.php or archive.php? Since I need to put this code inside the loop, I want the code to register on every post just like it registers in the single.php in the example I provided above. Something like the following, I presume? get_post_meta($post->ID, "user_submit_url", true); Let me know if I need to clarify anything.
If your Loop is constructed correctly `$post` will be set for each post in the loop in turn. You could also consider using `get_the_ID`. `get_post_meta($post->ID, "user_submit_url", true);` by itself won't do much. You will have to format and `echo` the information but that should retrieve your post meta data. For example, to generate a link (assuming your meta value is an URL and that you've save a string and not an array): $meta = get_post_meta($post->ID,'user_submit_url',true); echo '<a class="meta" href="'.$meta.'" target="_blank">'.$meta.'</a>'; If your theme has a `category.php` and you want this only on category archives put that code in `category.php`. `archive.php` is used by all archives that do not have a specialized template-- tag and author archives, for example. The template hierarchy is explained in the Codex.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, custom field, archives" }
Reorder plugin items in the admin menu Is it possible to reorder plugin menu items and custom admin items in the Admin menu without modifying the position in the plugin itself? I've tried using the method described here "Changing the Menu Order", but when you add a page link like `admin.php?page=pluginname`, it doesn't do anything. Guessing because it can't overwrite the position defined within the plugin. The Admin Menu Editor plugin works alright, but needing a plugin-less method to handle it to satisfy the higher-powers. :/ Anyone know of a way to get at this? Any help would be hugely appreciated!
Try taking just the name from the page admin link and see if it works. Something like this: function custom_menu_order($menu_ord) { if (!$menu_ord) return true; return array( 'index.php', // Dashboard 'separator1', // First separator 'edit.php', // Posts 'pluginname2', // Take the name from the page menu admin.php?page=pluginname2 'upload.php', // Media 'edit.php?post_type=page', // Pages 'edit-comments.php', // Comments 'pluginname', // Take the name from the page menu admin.php?page=pluginname ); } add_filter('custom_menu_order', 'custom_menu_order'); // Activate custom_menu_order add_filter('menu_order', 'custom_menu_order');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "admin, sort, admin menu" }
How many databases do I need? I have been asked to build another site for someone else. Eventually, I will turn it over to them. I will develop it locally, then take it live, then turn over full control. In the meantime I need a database for WP to interface with. Do I hook the new site into my existing database that I already have for my personal site or is it one database per website? I would hate to have export my database along with someone else's.
Multiple installs can share a single database, as long as each install has a unique table prefix defined in `wp-config.php` before going through the install process: /** * WordPress Database Table prefix. * * You can have multiple installations in one database if you give each a unique * prefix. Only numbers, letters, and underscores please! */ $table_prefix = 'client_1_'; I personally find it easier to just create a new database for each install, as my host allows an unlimited number of databases. I do still however make the table prefix unique for every install, as it could possibly protect against SQL injection attacks if a client installs a bad plugin with insecure code.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "multisite, database" }
Update post date of page when Visitor access that page? How to update post date of page to real time when Visitor access that page? Example: I write a post on May 28, 2013. And now, when I visit that post, it will change may 28 to June 8. How to do this?
You can hook into the action `the_post` (you get the post as parameter here) and run `wp_update_post()`. Make sure to clean up the _date_ properties and not to run on the admin side or when a post is called in a widget: is_admin() or add_action( 'the_post', function( $post ) { if ( ! is_singular() or ! is_main_query() ) return; $post->post_date = current_time( 'mysql' ); $post->post_date_gmt = ''; wp_update_post( $post ); }); **But** now you get a write operation on _every single request_. This will slow down your site. I wouldn’t do that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "date" }
Remove link from Page name in navigation bar I have a wordpress site and there is a navigation bar with menu and submenu. I want to remove link attribute from menu items that have sub menu. Is it possible? because i couldn't achieve to this by this function : `wp_list_page()`.
Use _Page Links To_ plugin by Mark Jaquith. Edit top level page and in section _Page Links To_ select _An alternate URL_ and enter # as an URL.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, permalinks, links" }
Where does wordpress store emails user enters when writing comments? I'd like to do some kind of newsletter. My idea is to get emails users entered when they were commenting my blog and send daily email to them all. Where does wordpress keep that emails? Is there any recommendation for doing some kind of newsletter/subscription? Which plugins do you recommend?
The email address associated with comments is kept in the `$wpdb->comments` table. Strictly speaking, that is the answer to the primary question. I'd be cautious culling email from comments as posting a comment is not clearly giving permission for you to send email. > Is there any recommendation for doing some kind of newsletter/subscription? Use a third party service like MailChimp or Constant Contact (not affiliated with either). Many hosts do not allow mass email through their mail servers. (Check your terms of service.) And, while I am not a lawyer, it seems to me that complying with the legal requirements for sending mass email can be tricky-- especially since I am not a lawyer. A decent service will deal with most of that for you. Plugin recommendations are off-topic but you can search the plugin directory. There are a lot of plugins related to this subject, including plugins that interface with the services mentioned, and others not mentioned.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "newsletter" }
Multisite for Multisite? Is there anyway I can allow users to create their own WordPress multisite network on my multisite network? It will be a premium service and will work much like reseller hosting, where the customer will pay the distributor and the remaining goes to the middleman as profit. Thanks!
The first step is to create Networks inside a Multisite Network. And it can be done with: * ### Networks+ > This plugin provides the interface to set up another network of sites within the install you already have. You may choose to run this additional network off a different domain entirely or a subdomain – it’s very flexible. * ### WP Multi Network > Adds a Network Management UI for super admins in a WordPress Multisite environment The second step (out of the scope of a Q&A site) is to inspect these plugins for public functions/methods and hooks to integrate with your custom commerce solution.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, multisite" }
Add background image/layout for single page? I'm seeing that a lot of sites (moz.com,hubspot.com) are using a background image as a layout. How do I add a single background image easily onto WordPress? I also want to add the layout here: < onto my blog. How do I do this?
This assumes that you want to add a background image for a specific page: Create your CSS class for the background you want. body.custombg {background: url("images/background.gif"); } In the header, you can use something like this to check for a specific page. <body <?php if(is_page(123)) echo 'class="custombg"' ?>> See Conditional Tags for more ideas of what you can do. As for the layout of that site, you should contact them and find out if they are using a publicly available theme or if it is a custom design.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, css" }
Underscores in custom fields While trying to perform a WP_Query using meta_query(), I had some trouble because the custom fields created by a plugin had `_` in the beginning of its name. Although I noticed it was stored this way in the database, I had no idea why it was there and thought I had to reference it without the underscore (for the record, that is wrong). Why do some custom fields start with underscores and others don't? What are the underscores used for? Are they mandatory in some circumstances?
Custom field names are arbitrary. The underscore hides it from the _Custom Fields_ metabox on the post editing page. When referencing these custom fields in `meta_query()` or other functions, the underscore has to be used. Source: conversation with @toscho, @rarst and @wyck in the chat room.
stackexchange-wordpress
{ "answer_score": 18, "question_score": 11, "tags": "custom field" }
What is WordPress file encoding? I noticed that WordPress files use UNIX end-of-line and UTF-8 without BOM. Is this a standard that should be used? Is there anything else to pay attention to? I noticed that Filezilla fails to transfer Macintosh end-of-line files properly to Windows or Linux servers. New line endings are missing. And sometimes they are doubled with different configuration. I'd like to avoid that if possible.
UNIX line endings (`\n`) and UTF-8 are just common code standards. As far as I can see, they are not even mentioned in the Coding Standards. Most (all?) core PHP files are just plain US-ASCII. Try to follow that path to keep your files as compatible as possible. If you use UTF-8, add a line at the start of a PHP file with an _Encoding Cookie or file variable:_ <?php # -*- coding: utf-8 -*- Many editors (Emacs, Vim, Sublime, Scite) will use that to set the proper encoding automatically. I have also seen: <?php # -*- coding: utf-8-unix -*- But I am not sure how compatible it is.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "customization, encoding, coding standards" }
Auto update date time 1 times per day? How to update automatically date time of page to current time only 1 time per day? Example: I write a post on May 28, 2013. And if today is June 9, it will change may 28 to June 9. And if today is June 10, it will change June 9 to June 10. How to do this? Thank you very much !
You're looking for wp_cron if ( ! wp_next_scheduled( 'my_task_hook' ) ) { wp_schedule_event( time(), 'daily', 'my_task_hook' ); } add_action( 'my_task_hook', 'my_task_function' ); And then you define `my_task_function()` updating the post date.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "timestamp" }
open image after clicking on single.php with different stylesheet in wordpress i have single.php like if(have_posts()) {while(have_posts()){ the_post(); //content displayed }} in the content i have some images. As i click on the image it opens in very simple manner without any background or header included in it. So how can i apply style on that page.
It sounds like your images are linking to the image file. When you upload images, try linking them to the attachment page instead, or look for a plugin that opens image links in a lightbox. Try both solutions and see which you prefer.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "attachments" }
Set a cookie only in single posts I'm trying to set a cookie when a user is on a single post. I'm keeping track of how many single posts he has read this month. I have two problems: I have a custom template and added the following code to my functions.php function articlesVisited() { if (is_single()){ $postNumber = $wp_query->post->ID; setcookie($postNumber,'visited',time()+60*60*24*31); } } add_action('init', 'articlesVisited'); First. The code inside is_single() is never reached when I visit a single post on my site. If I put an -else- block after it, it executes that. Second, the $wp_query->post->ID does not give me the ID of the post. I think that has something to do with global variables... Does anyone has experience with this?
`init` is too early (it happens before the main query), use the action `template_redirect` instead. And for the ID use `get_the_ID()`. Example: if ( is_singular() ) setcookie( get_the_ID(), 'visited',time() + ( DAY_IN_SECONDS * 31 ) );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "single, cookies" }
How to change widget's form color in admin? I have a simple question. How to change widget's form color in admin panel of wordpress (on widgets page) to make them more unique? Here is a simple example: !example
## Register/enqueue an admin stylesheet function my_admin_theme_style() { wp_enqueue_style('my-admin-theme', get_template_directory_uri().'/admin-style.css'); } add_action('admin_enqueue_scripts', 'my_admin_theme_style'); ## Then add rules of the form #widget-list div[id*="_archives-"], div[id*="_archives-"] { background:red; } Consider that proof of concept. I will leave it up to you to target the precise elements you want.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets, admin, css" }
How do I unserialize this? I don't know the most about WordPress, but I see some serialized data in the DB that a plugin creates. The plugin works just fine, so I guess it unserializes it just fine too. When _I_ try to unserialize() it, it fails and var_dump shows bool(false) for the result. This is the string I see in the database: a:1:{i:0;a:3:{s:4:"name";s:56:"Song → Black Meen : “So Clean (feat. Dullaah Jin)”";s:4:"file";s:98:" You might notice that the length fields don't match with the lengths of the values in the quotes. What's going on here? How do I unserialize this data?
Correct serialized string will be: a:1:{i:0;a:3:{s:4:"name";s:56:"Song → Black Meen : “So Clean (feat. Dullaah Jin)”";s:4:"file";s:93:" The second long string ( value of key "file" ) had incorrect lenght 98 which should be 93. You might ask why the first long string ( value of key "name" ) has lenght of 56. It looks like it should be 50. This string contains three special characters ( → “ and ” ) and their lenghts are 3 each therefore final length is 50 + ( 3 * 2 ) = 56.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
How to display posts from specific category using get_option function? I try to display posts from specific category only in a author page, using get_option function like in the code below but it does not work: <?php query_posts('cat='.get_option('admin_cat')); ?> However, if using the id number, works perfect. <?php query_posts( 'cat=6' ); ?> How can I use get_option function instead of ID number? Later edit: I apologize, it was my mistake that I wrote in admin option the category name instead of its id. However a code would be helpful to read both variants, like: if admin option the category is an id display its id if in admin option category is a name display its name Thanks
You can't use the category name to search for categories. You can use the slug. Be aware of the difference. A slug is normalized to lower case with spaces replaced by dashes. The slug for "Foo A" would be "foo-a". Using "Foo A" will not work. $admin_cat = get_option('admin_cat'); if (ctype_digit("$admin_cat")) { // this is an ID $qry = array('cat' => (int)$admin_cat); } else { $qry = array('category_name' => $admin_cat); } $my_query = new WP_Query($qry); As stated in a comment to your question, do not use `query_posts`. > It should be noted that using this to **replace the main query** on a page can **increase page loading times** , in worst case scenarios **more than doubling the amount of work needed or more**. While easy to use, the function is also **prone to confusion and problems** later on. See the note further below on caveats for details. > > < (emphasis mine)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, query" }
How can I add text to a single nav menu item? I'm working on a theme that requires the end-user to specify the current performance season using a custom admin panel I've created, ie. "2013/2014", "2014/2015" etc., which I can retrieve using `get_option('current_season');` On my custom nav menu I have a page titled "Season" that needs the aforementioned field inserted into it so it reads "2013/2014 Season" rather than just "Season". The walker tutorials I have looked at only seem to show examples of adding a class to menu items but I need to add specific text to one menu item. How can I achieve this?
You can try the `wp_nav_menu_objects` filter. This seems to work, but not sure what other side-effects it may have, you'll want to test thoroughly. function wpa_filter_nav_menu_objects( $items ){ foreach( $items as $item ){ if( 'Season' == $item->title ){ $item->title = get_option('current_season') . ' Season'; } } return $items; } add_filter( 'wp_nav_menu_objects', 'wpa_filter_nav_menu_objects' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "menus, navigation" }
How to change post date only 1 time a day? I have this code is_admin() or add_action( 'the_post', function( $post ) { if ( ! is_singular() or ! is_main_query() ) return; $post->post_date = current_time( 'mysql' ); $post->post_date_gmt = ''; wp_update_post( $post ); }); When refreshing the page, it will update to current time. But this will slow down my site. So how to update date time of page to current time **only 1 time per day** ? Example: I write a post on 5pm, June 6, 2013. And now, when I refresh page, it will change from 5pm, June 6 to 7pm, June 9. And in June 9, if I refresh the page, it will not change anything. Sorry for my poor English ! Thank you very much !
Compare the `post_date` with the current time and then test if the difference is greater than one day: is_admin() or add_action( 'the_post', function( $post ) { if ( ! is_singular() or ! is_main_query() ) return; // now minus last mod time in seconds $diff = time() - mysql2date( 'U', $post->post_date ); if ( DAY_IN_SECONDS >= $diff ) return; $post->post_date = current_time( 'mysql' ); $post->post_date_gmt = ''; wp_update_post( $post ); });
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "timestamp" }
What is content.php file that is needed for Jetpack infinite scroll plugin? I'm currently learning how to use Jetpack infinite scroll plugin, while going through the documentation I came across 'render' section: < It uses default loop, which I actually need to customise, it also says that if I have content.php file in my template than I'm good to go and can omit render argument. However I don't know what content.php file is for. As for the loop and the markup of each post, those are defined in my index.php, single.php and page.php files. Could you please explain and give example of what content.php page is, where it should be located and how can it be used. I'm speculating that its a file where I can paste just my loop and post markup bit, so perhaps I can than somehow include content.php file in my index.php, single.php and page.php files maybe? Not sure. I did look for this in the codex, but surprisingly couldn't find explanation of content.php file.
There is no standard for a `content.php` in WordPress, that’s why you cannot find in the Codex. Some themes use it to render the post content. So instead of … while ( have_posts() ) { the_post(); ?><li <?php post_class(); ?>> <?php the_title( '<h2><a href="' . get_permalink() . '">', '</a></h2>' ); the_excerpt(); wp_link_pages(); ?></li> <?php } … they use … while ( have_posts() ) { the_post(); get_template_part( 'content', get_post_format() ); ?></li> <?php } But you could use _any_ name and it would still work. Jetpack follows a convention from WordPress’ last default themes here; these are using a `content.php`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "templates, plugin jetpack" }
Automatically Marquee Code scrolling with recent post title? I want Automatically Marquee Code scrolling with recent post title in Header. any one can tell me. my marquee code <div id="breakingNews1"><img src=" SIZE="4" FACE="TT" COLOR=green><marquee width="820">any text here </marquee></FONT> </div> how i can do i. anyone can tell me? my site <
As I told you in chat, you just need the recent posts and can add any markup you need: // functions.php function recent_inaccessible_posts() { if ( ! $recent = wp_get_recent_posts(array(), OBJECT ) ) return; $out = '<marquee><ul>'; foreach ( $recent as $r ) $out .= '<li><a href="' . get_permalink($r->ID) . '">' . get_the_title($r->ID) . '</a>'; print "$out</ul></marquee>"; } Call it wherever you need it with `recent_inaccessible_posts();`. Be aware, scrolling text is almost inaccessible for many users. I would never use it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "html" }
Cannot find Home link in Pages on Dashboard I cannot see the Home page link in the WordPress menus section. Here's how the Pages box look like this: !screenshot How can I get the link of Home?
Create a custom link and drag it to the menu: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus" }
Get file headers in custom file in my one of my plugins i have modules (kind of like plugins in a plugin), is there a function like `get_plugin_data()` or `wp_get_theme()` that will allow me to get the header section of a custom file (by passing the path as a parameter)? By heading section i mean /* Plugin Name: Name Of The Plugin Plugin URI: Description: A brief description of the Plugin. Version: The Plugin's Version Number, e.g.: 1.0 Author: Name Of The Plugin Author Author URI: License: A "Slug" license name e.g. GPL2 */ Thanks to @toscho the correct solution was $default_headers = array( 'Module Name' => 'Module Name', 'Test Header' => 'Test Header', ); $file_data = get_file_data(dirname(__file__).'/some-file.php', $default_headers); print_r($file_data);
Use `get_file_data( $file, $headers )`: $file_data = get_file_data( __FILE__, array ( 'Plugin Name' ) ); echo "the name is " . $file_data[0]; Make sure the first parameter points to an existing file. It will find all lines that are formatted like regular plugins headers or the headers of a `style.css`. In my plugin _T5 Opera Speed Dial Preview_ I use it to show the link to my bug tracker: $data = get_file_data( __FILE__, array ( 'Feedback URI' ) ); return empty ( $data ) ? '' : $data[0];
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "plugin development, theme development, headers, get plugin data, wp get theme" }
Include title and content of one page in another page In this question contents of another page can be rendered to another page, but how do I do it for the title too? Can I just go `$content = apply_filters('the_title', $post->post_content);`? But what do I add at the second argument? From how it looks like, it's an array right? Which one stores the actual title of the page?
Use `get_the_title()`: $page = get_page_by_title( 'About' ); $title = get_the_title( $page ); You could also use `$page->post_title`, but `get_the_title()` will let plugins access the title, which sometimes quite useful.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, title" }
Export data as CSV in back end with proper HTTP headers I wrote a plugin that displays all products in a woocommerce store in admin settings option, now I want to add a link to download the products as CSV file. The problem is, when I click the link I get a permission error saying I don't have permission to view this page. Here's my code: function extra_tablenav($which) { if ($which == "top") { echo '<h3 style="display:inline">' . __('These products are currently in the database:') . '</h3>' . '&nbsp;&nbsp;&nbsp;' . '<a href="' . admin_url('admin.php?page=download_csv.php') . '">' . __('Export to CSV') . '</a>'; } } How can I fix those permissions?
Do not point the URL to `admin.php`, use `admin-post.php` instead: '<a href="' . admin_url( 'admin-post.php?action=print.csv' ) . '">' In your plugin register a callback for that action: add_action( 'admin_post_print.csv', 'print_csv' ); function print_csv() { if ( ! current_user_can( 'manage_options' ) ) return; header('Content-Type: application/csv'); header('Content-Disposition: attachment; filename=example.csv'); header('Pragma: no-cache'); // output the CSV data } If you want to make the data available for anonymous users (not logged in), then register the callback again with: add_action( 'admin_post_nopriv_print.csv', 'print_csv' ); … and remove the capability check from the function.
stackexchange-wordpress
{ "answer_score": 26, "question_score": 8, "tags": "plugin development, wp admin, permissions, csv" }
apply_filters to featured image I have a page where I have embedded the page using these lines of codes at function.php: //------Embed Content------ //Title function CustomFunction_ShowPage_Title($id) { $post = get_page($id); $title = apply_filters('the_title', $post->post_title); echo $title; } //Content function CustomFunction_ShowPage_Content($id) { $post = get_page($id); $content = apply_filters('the_content', $post->post_content); echo $content; } How do I do this for featured images too? do I simply replace `the_content with` with `the_post_thumbnail`? if so, what do I put on the second parameter? do I simply go `$post->post_thumbnail`?
Use `get_the_post_thumbnail( $id )`: $thumb = get_the_post_thumbnail( $id, 'post-thumbnail' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, functions, filters, post thumbnails, embed" }
search content of pages and list in wp-admin I am developing a plugin, and I want to display a page that lists every page on the site that is using a specific shortcode defined by my plugin. I assume that I need to manually search wp_posts, but I am curious if there is a built in function or a better way to do this. Thanks so much!
You can specify a search term in a `WP_Query` or `get_posts()` call: $pages = get_posts( array ( 's' => '[shortcodename', 'post_type' => array ( 'page', 'post' ) ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, plugin development, search" }
how to get wordpress user id when user register im creating wordpress user using `wp_create_user()` function and when user creating i want to add that users userid to custom table, this is the way i tried add_action( 'user_register', 'atuser_info'); function atuser_info( $user_id ) { global $wpdb; //$prefix=$wpdb->prefix; $query_userinfo = "INSERT INTO user_info (id,fname,lname,address_1) VALUES (".$user_id.",".$_POST['fname'].",".$_POST['lname'].",".$_POST['address_1_step2'].")"; $wpdb->query($query_userinfo); }
If `wp_create_user` executes successfully, it will return the id of the created user. [[Codex]]( Here it is in action with an error handler. $user_id = wp_create_user(); if( is_wp_error($user_id) ) { echo $user_id->get_error_message(); } else { //add into custom table echo $user_id; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, wp register script" }
Searching With Apostrophe I'm having trouble with my custom theme's search function. I have a number of posts with apostrophes in the title. For example, `McDonald's`. However, when I try searching say `McDonalds`, the post won't return in the search results. How can I go about making sure that `McDonald's` would return in the result even if the user didn't include the apostrophe.
Your question isn't much of a WordPress related question, more like a MySQL question. But I have sort of a solution in my head: You could go with a custom query and a replace on the apostrophe: SELECT * FROM `table` WHERE REPLACE( `column`, "'", "") LIKE REPLACE( 'string', "'", "" ) For a combined search: SELECT *, REPLACE( `column`, "'", "" ) AS `custom` WHERE `column` LIKE 'string' OR `custom` LIKE 'string' It isn't worlds most beautiful solution, but you could give it a shot.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "query, search, mysql" }
Multi language site using only .mo and WPLANG Hello world/ Bonjour le monde, What technical limitations exist that would prevent the following from working (assume all static content with translations made in .mo file) Pseudo code: For every request: * Check if query string contains field :myLang: * If value of :myLang: equals "en_US" * Then ~somehow change WPLANG to "en_Us" (Or force Wordpress to behave as if WPLANG was actually set to '') * Else- serve request as French using the fr_FR.mo as defined in wp-config.php I am vaguely aware that it has something to do with the way Wordpress is initialized. I know WPLANG can't be changed on the fly.
> I am vaguely aware that it has something to do with the way Wordpress is initialized. I know WPLANG can't be changed on the fly. It's how PHP works: You can't change an already defined constant. But there're filters for that. The following plugin is a sketch that you could use and try to see if this direction fits your needs. <?php defined( 'ABSPATH' ) OR exit; /** * Plugin Name: (#102471) Query Locale */ add_filter( 'locale', 'wpse_102471_locale', 20 ); /** * Callback to filter the locale/textdomain. * Assumes that you got a `lang` query var * @param bool $locale * @return mixed string/bool $locale|$GLOBALS['wp_query']['lang'] */ function wpse_102471_locale( $locale = false ) { global $wp_query; if ( isset( $wp_query['lang'] ) ) return $wp_query['lang']; return $locale; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multi language, localization, wp config" }
Get the terms of a custom taxonomy for a specific author in author template I am using a custom post type in my website and a custom taxonomy for it. An author selects one or many terms before publishsing its post. My goal is to display authors pages in front end, so I am using `author.php` template file. This file is by default displaying the archive of posts written by the specific author. How can I add to this file the list of the custom taxonomy terms for the author published posts? I give the following example if I wasn't clear in my explanation: if Author-x has published: **post1** with term1 , term2, term3 **post2** with term2, term5 **post3** with term1 then, in Author-x page I will have : term1, term2, term3, term5. It is exactly the same principle as in user page in stack exchange. As you can see, there is a list of tags for each user which are tags of posts the user contributed in. Thank you for your usual help.
First get a list of the author posts then loop over the each post and get the terms used ex: function list_author_used_terms($author_id){ // get the author's posts $posts = get_posts( array('post_type' => 'custom_post_type_name', 'posts_per_page' => -1, 'author' => $author_id) ); $author_terms = array(); //loop over the posts and collect the terms foreach ($posts as $p) { $terms = wp_get_object_terms( $p->ID, 'taxonomy_name'); foreach ($terms as $t) { $author_terms[] = $t->name; } } return array_unique($author_terms); } //usage echo implode(", ",list_author_used_terms(1));
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "custom post types, custom taxonomy, author, terms, author template" }
Change path/url of admin-bar.min.css Does anyone know where admin-bar.min.css is registeded/included? Im trying to add a slash in front of admin-bar.min.css, so the admin bar will work correctly on all pages. Im playing arround with a wordpress site with dynamicaly generated urls, and right now the admin bar is the last thing I need to fix, only I cant find it. All help is much apriciated :)
`admin-bar.min.css` is not registered via the normal `wp_register_style` channels. It, and the other default styles, are registered by `wp_default_styles`, which registers them by directly manipulation the `$styles` object, though I don't know what good that is since there are no hooks and you shouldn't be hacking core files. You should still be able to deregister that style and re-add it. If that doesn't work I expect that you'd need to alter the `$styles` object yourself.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls, admin bar, wp register style" }
How to save a viewer specific option A minimal example of my problem would be * default background colour is white * a custom sidebar widget offers to switch background colour to green * when switched to green, background shall stay green while exploring the blog Is there a standard interface in Wordpress for saving a global PHP variable $bgcolor to the viewer and read it from him anytime he browses to another blog page. (I'd like to avoid setting a cookie "by hand")
> Is there a standard interface in Wordpress for saving a global PHP variable $bgcolor to the user and read it from him anytime he browses to another blog page. There is nothing that will automagically do it for you but it sounds like you just need to save a little bit of user meta, and of course retrieve it. Since you asked about saving the variable, I am going to assume that the custom sidebar widget that switches the background color already works. Just add code, based on the two Codex entries above, that checks the user meta and saves changes. If you post your code, I may be able to give a more elaborate answer. If you are talking about generic visitors, and not WordPress users, setting a cookie is your best choice. There are no built in generic "cookie setter" functions that I am aware of. WordPress itself uses PHP's `setcookie` in a fair few places, for example in `wp_set_auth_cookie`, and I don't know why that function would need a "helper". It is fairly straighforward.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "globals, cookies" }
Delete post based on a custom field? I am trying to delete a post based on a custom field value called randomid. $querystr = " DELETE FROM $wpdb->posts LEFT JOIN $wpdb->postmeta WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_key = 'randomID' AND $wpdb->postmeta.meta_value = '$randomID'"; Which gives me something like DELETE FROM wp_posts LEFT JOIN wp_postmeta WHERE wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'randomID' AND wp_postmeta.meta_value = '070313wIOLTxv'; But i get a mysql syntax error, what am i doing wrong?
You don't have a `ON` for your `LEFT JOIN`, I guess the `WHERE` statement you use has to be the `ON` statement. You should use this query instead: $querystr = " DELETE FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE $wpdb->postmeta.meta_key = 'randomID' AND $wpdb->postmeta.meta_value = '$randomID'"; Reference here: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom field" }
WP-Snap too slow (caused by WP_Query?) I have a website with 10.000 posts... WP Snap alphabetizes the posts and puts it out with WP_Query, but it is slow as hell, which is very frustrating. My question would be: what can I do about it? Is there any alternative to wp_query? Or is the cause of this problem something else?
The only answer to this question is: **don't use this plugin, because it is outdated**. I couldn't write a better code, so I am going to use alternatives like `A to Z listing` and `WP-Glossary`. I hope the developer of this great plugin will update the code, because it is a very useful plugin if it could contain more than 1000 posts... Thanks for your comments.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, wp query, query posts, query" }
Automatically deactivate link for attachments It's probably super easy. I know it can be done when uploading stuffs to WP but I wonder if there is a simple snippet or setting to automatically deactivate link on attachment. For example : I do not want : `<a href=""><img src="" /></a>`but I want `<img src="" />` I've veen thinking about a regex to do this but maybe there's a less tricky way to do that. Hope this is not a duplicate, I've been searching on wpse, found nothing related. Thanks in advance.
With markup embedded into the content there is no less tricky way than regex to do it, save perhaps a markup parser like SimpleHTMLDom function remove_image_link_102512($content) { $pattern = '|<a.*?href="(.*)".*>?(<img.*?/?>)(?:</a>)?|'; $content = preg_replace($pattern,'$2',$content); return $content; } add_filter('the_content','remove_image_link_102512'); As with all regex + markup solutions, I'd test that thoroughly. Of course, as no saved data is updated it won't catastrophically or permanently break anything if it fails.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "attachments, links" }
Checking 2 dates against todays date I am trying to display data from a custom post type, based on the date that the event will occur. The date is set in a meta box in the cpt. My code so far is: $today = date('d/m/Y'); $p_date = get_post_meta($post->ID, '_cmb_training_date', true); $p_date2 = get_post_meta($post->ID, '_cmb_training_start_date', true); if($p_date > $today) { // stuff } This works fine (only shows events after todays date) but I want to add in another event type (`$p_date2`) as well but if I do: if($p_date > $today || $p_date2 > $today) { // stuff } It displays all the posts from the CPT The date formats are all the same, so it's got to be with my if statement any ideas?
For date manipulations you should use the DateTime class. Also, dates should be stored in `Y-m-d` format (if you're storing them differently you can create the DateTime object from a specified format: < (php 5.3+) - but I recommend storing it in the unambiguous Y-m-d format ). The following assumes `Y-m-d` formatin the post meta: $today = new DateTime( 'now' ); $p_date = new DateTime( get_post_meta($post->ID, '_cmb_training_date', true) ); $p_date2 = new DateTime( get_post_meta($post->ID, '_cmb_training_start_date', true) ); if( $p_date > $today || $p_date2 > $today) { // stuff } As you mention in the comments. You can also easily obtain year/monthy/day information: if( $p_date2->format('m') == '01' ){ //$p_date2 is in January }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
Post selector as Custom Field I would like to add a custom field for user to select a existing post or page to a post. (eg as related post, or as similar post...) a way that the user can browse trough exisisting and published posts and then select 1, via post editing screen, just like the "LINK FROM EXISTING CONTENT" tool at the TinyMCE
The excellent My Metabox class by bainternet does exactly what you are looking for. Add a post dropdown list with $my_meta->addPosts('posts_field_id',array('post_type' => 'post'),array('name'=> 'My Posts ')); And it will create a meta box with posts dropdown (you can change this to a checkbox list if you want to be able to select more than one post) My Metabox class can be customized to your liking with little effort. Edit: It's My Metabox Class not Tax Meta Class, which lets you create taxonomy meta data in the same way.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom field, customization" }
Mysql Query to Delete Duplicate Wordpress posts? I have a lot of duplicate posts. So, how to delete them (only keep 1 post). If they have same title, they are duplicate posts. Thank you very much ! Have a nice day !
I'm not entirely sure you can do this with a single query in MySQL as you can't delete from tables which you reference in a sub-query. I would actually recommend doing this using wp-cli and using the WordPress API to delete the duplicate posts (which will also delete any post meta and associated term references): global $wpdb; $duplicate_titles = $wpdb->get_col("SELECT post_title FROM {$wpdb->posts} GROUP BY post_title HAVING COUNT(*) > 1"); foreach( $duplicate_titles as $title ) { $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title=%s", $title ) ); // Iterate over the second ID with this post title till the last foreach( array_slice( $post_ids, 1 ) as $post_id ) { wp_delete_post( $post_id, true ); // Force delete this post } } Hope this helps.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "post duplication" }
Is there a author_update action? Is there an action you can tie into whenever an authors information is updated. (ie they update their display name). If not is there any way to tie into this?
There's the `edit_user_profile_update` and `personal_options_update` actions that runs after a user is updated, with access to the user object. There's also a variable `update_{$meta_type}_meta` action that runs when meta of type `user` is updated.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks, author, actions" }
Add Schema Image Designation Inside a Wordpress Function? I would like to add itemprop="articleSection" to a thumbnail. <?php the_post_thumbnail('thmb-index'); ?> This is what I've tried: <?php the_post_thumbnail('post-thumbnail',array('itemprop'=>'image')); ?> How can I do this in the most simple and effective way? Preferably, I would like to incorporate it into `<?php the_post_thumbnail('thmb-index'); ?>` itself, not functions.php.
What you are trying to do works for me. That is, this works when I try it: the_post_thumbnail('post-thumbnail',array('itemprop'=> 'articleSection')); I get the `itemprop` attribute is my `<img` tag. If that isn't working for you I can only guess at why. Possibly there is a filter causing problems. For a more global solution, the following will add that `itemprop` to anything that uses the `wp_get_attachment_image_attributes` filter, which `the_post_thumbnail` does. function alter_att_attributes_wpse_102551($attr) { $attr['itemprop'] = 'articleSection'; return $attr; } add_filter( 'wp_get_attachment_image_attributes', 'alter_att_attributes_wpse_102551'); You may need conditions to prevent that from running as globally as it will left as it is.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "html" }
wp nav menu - highlighting current page not working properly I'm trying to highlight the current page in the wp nav menu. I've read through the codex and found .current-menu-item, which I'm using in my CSS.. However it's not working. What am I missing? css #header nav { float: left; padding-left: 25px; padding-top: 12px; } #header nav ul li { display: inline; } #header nav ul li a { color: #333333; font-family: amatic; font-size: 150%; padding-right: 25px; } #header nav ul li a:hover { color: #c6e000; } #header nav ul li a:last-child { padding-right: none; } #header nav .current-menu-item { color: #c6e000; } html/php <div id="header"> <nav> <?php wp_nav_menu( array('menu' => 'nav' )); ?> </nav><!-- end nav --> </div><!-- end header --> live site
Since the text that displays your navigation is made out of anchor points, which has the `color: #333333;` assigned, you'll have to add the `.current-menu-item` color to the anchor itself: `#header nav .current-menu-item a { color: #c6e000; }`
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "menus, css" }
Search tag within category How do I search a tag within a category? like if a user is viewing a post that belongs to category "Romance" and the user clicks on one of the tags like for example "blonde" it should list all posts tagged "blonde" within category "Romance". How can I do this?
I'm not really sure how to do this, but I found a plugin that seems to be able to do this. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, tags, archives, list" }
Permalink structure as code in back-end? I have this `permalink structure`: `/%year%/%monthnum%/%postname%/` What I want to is, output the link of a post in the back-end and let users input a postname, that will automatically lead to that post (if it exists, otherwise 404)... So, I have this: function transform_pseudo_anchor_wpse_101201($match) { if (isset($match[1])) { return '(link: <a href=" title="'.$match[1].'">'.$match[1].'</a>)'; } } $content = preg_replace_callback( '%\(link: ?(.*?) ?\)%', 'transform_pseudo_anchor_wpse_101201', $content ); echo $content; Of course, this does not work... But how can I make it work? So I want the get the exact link if someone links to a post that exists... So after example.com, the year/monthnum and postname has to come...
Your code works to create links, and WordPress should make a valiant effort to find the correct post, but it doesn't get complete permalinks. To do that you will need to query the database for the post and construct a permalink if one is found. function transform_pseudo_anchor_wpse_101201($match) { global $wpdb; if (isset($match[1])) { $name = sanitize_title_with_dashes($match[1]); $p = new WP_Query( array( 'name'=>$name, 'post_type' => 'post', 'posts_per_page' => 1, 'suppress_filters' => true, 'ignore_sticky_posts' => true ) ); if (!empty($p->posts[0])) { $link = get_permalink($p->posts[0]); return '(link: <a href="'.$link.'" title="'.$match[1].'">'.$match[1].'</a>)'; } else { return 'nada'; } } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, customization, users, links" }
How to print [embed] code in wordpress I would like to print the following code in wordpress. [embed] But every time I use that code in the wordpress editor, it automatically embeds the video. Is there a way to print it. I've tried `pre` and the answer mentioned here < But its still not working.
There is a special trick to do that with simple shortcode like [gallery]: `[[gallery]]` But I do not know if it works with enclosed shorcodes EDIT: I guess you have to use solution 2 provided by toscho > write it as as `&#x5b;` or `&#91;`; If you have to write it from time to time you could use the Quicktags API
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, tinymce" }
Custom shortcode that writes to file I'm trying to maybe do too much in a shortcode call. Here's the code I have: //[rand] function randnumber_func( $atts ){ $digits = 4; $randnumber = rand(pow(10, $digits-1), pow(10, $digits)-1); $space = "\r\n"; $myFile = "offer_codes.txt"; $fh = fopen($myFile, 'a+') or die("can't open file"); $stringData = date("F j, Y, g:i a") . " - " . $randnumber; fwrite($fh, $stringData.$space); fclose($fh); return $randnumber; } add_shortcode( 'rand', 'randnumber_func' ); I want to create a random 4 digit number and have it printed to the page. I also want to take that random number, append the date to it, and have that written to a text file. It works in PHP, but not when I call it via a shortcode. Is something it Wordpress stripping it out or do I have it written incorrectly for the shortcode function?
Your code works for me on a development server. As is, it saves to the site root directory. My guess is that you are trying to write to a directory to which the server does not have write access. I would suggest saving to `wp-content/uploads` or some other directory where you should reasonably have write access. $upload_dir = wp_upload_dir(); $myFile = $upload_dir['basedir']."/offer_codes.txt";
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode" }
List Categories (wp_terms) and count posts I have a problem (of course) and I'll go straight to the point: I need to list all the custom categories and count the posts for each category eg. * Category 1 (xx posts) * Category 2 (yy posts) * etc.. I tried a couple of queries but with no luck. All these categories are stored in the wp_terms table, how do I list them since I've seen that there isn't, apparently, any elations between wp_terms and the posts? Worthless to say that i've tried wp_list_categories but it shows just "Uncategorized" since the website I'm using, uses custom post rather than "default" categores. Thanks in advance!
After struggling a little bit, I found a solution writing this: <?php $cat_args = array('orderby' => 'name', 'show_count' => '1', 'hierarchical' => '0','taxonomy' => 'here goes the taxonomy');?> <ul> <?php $cat_args['title_li'] = ''; wp_list_categories(apply_filters('', $cat_args)); ?> </ul>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, custom taxonomy, customization" }
plugins_url('',__FILE__) != WP_PLUGIN_URL with sym links For one of my many sites, `plugins/plugin-name` is a sym link pointing to `universal-install/wp-content/plugins/plugin-name`. `echo WP_PLUGIN_URL` displays what I expect. `echo plugins_url();` displays what I expect. `echo plugins_url('',__FILE__)` displays what I expect followed immediately by the absolute path to the universal plugins directory. Is there any way I can fix `echo plugins_url('',__FILE__)` to return only the expected result?
When writing a plugin, I define a few constants including the path to the plugin's root folder, and its "name" as used in some admin hooks: define('WPSE_102681_PLUGIN_NAME', basename(dirname(__FILE__)) . '/' . basename(__FILE__)); I've found that `plugins_url()` happily takes that constant, which is useful when referencing files from subfolders of the plugin, like so: echo plugins_url('images/information.png', WPSE_102681_PLUGIN_NAME); Maybe it'll fix your problem.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins url, linux" }
Returning Variables back into a template If I put a function that I want to use in a template I can put it into functions.php function myfunction(){ echo 'My String'; } `add_action('myfunction','myfunction');` and in a template file put: do_action('myfunction'); This appears to only work if writing something out to the screen. If I wanted to return a variable instead to the page. E.g. function myfunction(){ return 'My String'; } $string = do_action('myfunction'); and capture it instead of print it. How would I do it?
There's filters for that. Example: add_filter( 'template_filter', 'wpse_102706_filter_callback', 10, 2 ); function wpse_102706_filter_callback( $defaults, $case ) { $args = wp_parse_args( array( 'some_key' => 'some_modified_value' ), $defaults ); return $args } Then in your template just add in the defaults: apply_filters( 'template_filter', array( 'some_key' => 'default_val' ), 'single' ); More info in Codex about the Plugins API.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "theme development, functions, themes, templates, page template" }
Get a list of galleries from an album in NextGEN Gallery I want to get a list of galleries of a certain album. Than I would create a link to this galleries. How do I get the list of galleries in PHP? I saw that there is some code like global $nggdb; $gallery = $nggdb->get_gallery ($galleryID, 'sortorder', 'ASC', true, 0, 0); but is there some documentation which functions I could use?
Put this into your page template: <?php global $nggdb; $galleries = array(); $album = $nggdb->find_album(1); foreach( $album->gallery_ids as $galleryid ){ $gallery = $nggdb->find_gallery($galleryid); $galleries[$galleryid]['title'] = $gallery->title; $galleries[$galleryid]['url'] = get_bloginfo('url') . '/portfolio/?album=all&gallery=' . $galleryid; } foreach($galleries as $category){ echo '<a href="' . $category['url'] . '">' . $category['title'] . '</a><br />'; } ?> You have to adapt the album id and you need to link to a page where the album code of NGG is active. All functions can be found in /wp-content/plugins/nextgen-gallery/lib/ngg-db.php.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 1, "tags": "plugins, php, gallery, plugin nextgen gallery" }
Exporting just posts of a specific category I have found the export tool particularly useful for moving posts from sites to site, and even once wrote an extension for Elgg to export its content into wordpress export format for migration to BuddyPress. However, I now find I'd like to export just the posts of a single category, so that I can put those posts on a different wordpress install whilst leaving the other posts on the original site. Given the number of posts on the site, I'd rather not have to export everything and manually edit the xml file. Is there a way I can export posts of just one category into a standard wordpress import/export xml file? The site being imported to is on the same multisite install, with shared user base, so post and comment attribution should be preserved.
The default exporter will do this. Instead of selecting "All Content", choose "Post" and then a category. !enter image description here
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "categories, import, export" }
Random element in get_post_meta array I have a custom field that contains a list of comma separated colors. I want to randomly select one of those colors. If get_post_meta returns an array I thought I could randomly pick from that array. If I try to echo $rand_color_value it just gives me the whole array How can I randomly select one color from the list in the custom field. $agrs = array( 'post_type' => 'page', 'tag' => 'colors' ); $colorLoop = new WP_Query($agrs); if($colorLoop->have_posts()): while($colorLoop->have_posts()): $colorLoop->the_post(); $theColor = get_post_meta($post->ID, 'colors', false); /*random color*/ $rand_color = array_rand($theColor,1); $rand_color_value = $theColor[$rand_color]; echo $rand_color_value; ?> <?php endwhile; endif;?> <?php wp_reset_postdata; ?>
As the content of the meta data is actually a string (according to your comment), your code won't work. `get_post_meta()`, respectively `get_metadata()` will only deserialize the content if it's actually serialized. So, if you can't change how the data is saved, ie make sure that an actual `array` or already serialized content is passed to `update_post_meta()`, then you have to manually explode your data into an array: $theColor = get_post_meta($post->ID, 'colors', true); $theColor = explode(',', $theColor);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "array, post meta" }
Is it possible to have a Theme with built-in physical page files? I am creating a theme and was thinking if it would be possible to create pages within my theme folder that would reflect the wordpress url + path. So for example I could when accessing: < it would looks for about.php or about.html inside my theme folder? I have obtained success doing this but handling the `is_404` method and then rendering the page with `get_template_part($pathname)`, however, every page will output the 404 response status which is not viable? Is there any other way to accomplish that? I wish there was some kind of url aliases I could grant for my theme and could use it. Thanks in advance
WordPress would allow this (sort of). You would still need to create an About page in the back end, but you can tailor your display for such a page 2 different ways: 1. Page Templates 2. Page template hierarchy \- What this means is there is a certain order of what WordPress is looking for when displaying any page/post. Check out the image here for a more direct understanding. For pages specifically, the default is page.php, but page-$slug.php has higher priority. So in this case, you could make page-about.php, and alter what is displayed on that page. I would **strongly** suggest keeping the main content within that page, but this is how you add additional items to a page structure, such as sidebars, "Related Items" links, etc.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, page template, get template part, paths" }
How to over-ride a file in a plugin? I have a third party plugin that I'm using for a photo gallery (NextGen). However, with my black background, the loader gif animation looks pretty bad. I found a better loader gif and replaced the one from the plugin. I already know this is not ideal because the next update of the plugin will overwrite my custom gif. The gif is located at: `/wp-content/plugins/nextgen-gallery/images/loader.gif` Is there a clever way to leverage my child theme's `functions.php` file to tell this plugin to use a different URL for the gif? As far as using my child theme's CSS to override, that would be easiest if it was a viable option. However, the loader's URL is not coming from the plugin's CSS file.
Use a rewrite rule in your .htaccess: RewriteRule ^path-to-images/ajax-loader\.gif /path-to-replacement.gif [L] Make sure to set this above the WordPress rules.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins, functions, child theme, plugin nextgen gallery" }
Wp Dropdown Category Not Show Current As Title Im using wp_dropdown_categories for a page. Issue im having is i dont want it to show the current category that the page is on as the title, i want it always to display the "Select A Category" text i have placed in the options. Current code is: wp_dropdown_categories( 'show_option_none=Select A Category&show_count=1'); Is there a way to do this?
You can use `get_query_var( )` to fetch the current category: $cat = get_query_var( 'cat' ); You can use this `$cat` in the exclude parameter of `wp_dropdown_categories( )` to hide the current category: $args = array( 'show_option_none' => __( 'Select A Category' ), 'show_count' => 1, 'exclude' => $cat ); wp_dropdown_categories( $args );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, dropdown" }
Wordpress Settings API settings not saving for some users I created a plugin you can see here: < Some users are saying that settings aren't saving. For me it's working fine but I'm fairly new to php and absolutely new to the settings api, so I'm just wondering if I did something wrong or incorrectly that could be leading to this? Though ike I said, it's working just fine for me that's why I'm confused... Here's the pastebin of my options.php: <
Here are few remarks after skimming through your code: * you are using options name like `id`, `title` and `global`. You should use a prefix on these names, like `vegas_`, to avoid possible problems with other stuff using these option names. * you should let the users know about validation problems (check out the `add_settings_error()` function) * use `trim()` on your text fields values when you save. * use `esc_attr()` to escape your HTML attributes. * develope your plugin with `WP_DEBUG` activated, so you can catch any errors before you ship your plugin. Hopefully this will bring you closer to a resolution ;-) ## Reference: < < <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "options, api" }
How do you put your own rules into .htaccess? Is it possible to put your own rules in .htaccess but still give WordPress control over 'it's bit'?
This is the default. WordPress will add markers before and after its rules and not touch anything else: # BEGIN WordPress # WP rules here … # END WordPress Just make sure to set your rules before the WordPress rules, because WordPress’ rewrite rules are rather greedy (they have to), so later rules will probably not apply.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, htaccess" }
how to get page id of a page using page slug I'm pretty new to WordPress and I was wondering if I could get a `page id` with its `slug`. Is it possible please let me know?
Use `get_page_by_path($page_path)`: $page = get_page_by_path( 'about' ); echo get_the_title( $page ); This will return a regular post object. **Documentation:** < <
stackexchange-wordpress
{ "answer_score": 74, "question_score": 51, "tags": "php, slug, id" }
Woocommerce Product Page edit "from" text Is there a way to change the "From:" text that denotes the lowest available price for each particular product within the shop? I'm asking this as, on our shop we offer A4 samples within the Wallpaper sections, and the program sees this as the lowest available price. However this is somewhat misleading. So, is it possible to change this text to "A4 Sample:" Alternatively, is there away to add text. Either before the "From:" text, or to the end of the field, after the price? If none of this is possible, is there a way to get the default price of products in the Wallpaper section to be that of the Rolls of Wallpaper?
You can use a filter to change the text or the min price, this will affect all variable products. add_filter('woocommerce_variable_price_html', 'custom_price_text', 10, 2); function custom_price_text( $price, $product ) { $price = ''; $price .= '<span class="from">' . _x('A4 Sample', 'min_price', 'woocommerce') . ' </span>'; $price .= woocommerce_price($product->get_price()); return $price; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
setlocale for date So I purchased a premium wordpress theme, but I can't get through its Polish localization - the dates outside the_time or the_date are displaying in English (default server's language). I read that I have to use setlocale(LC_ALL, 'pl_PL'); to change it, but I don't know in which file or where it should be included and/or if I need something more. Below is an excerpt of code displaying English date: $event_date = get_post_meta(get_the_ID(), 'event_date'); $event_from_time = get_post_meta(get_the_ID(), 'event_from_time'); $event_to_time = get_post_meta(get_the_ID(), 'event_to_time'); $event_address = get_post_meta(get_the_ID(), 'event_address'); echo date('j F Y', strtotime($event_date[0])).' '.$event_from_time[0].' do '.$event_to_time[0]; I appreciate your time and help.
Use `date_i18n( $format, $i );` echo date_i18n('j F Y', strtotime( $event_date[0] ) ) . ' ' . date_i18n('j F Y', strtotime( $event_from_time[0] ) ) . ' do ' . date_i18n('j F Y', strtotime( $event_to_time[0] ) ); See also: How to integrate get_post_time with date_i18n function?
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "translation, date time, language" }
Getting the current post number / make posts increment I'm creating a site similar to < in that there's a bunch of posts on the site, and only one post gets shown per page. I want to add a counter that says something like: "Issue #210" at the top of each post, as they have done with < This would increment with each new post. I've seen it out there to use `wp_query->current_post`, but that only works when you run through a loop. I'm only showing one post per page, so `wp_query` always returns 0. Any ideas how I can make my posts increment? Thanks!
The one persistent numerical thing about post is ID, however it is sequential for _all_ posts, so you will have gaps if using it. It would be easiest to assign a number and store it in custom field on post creation. Probably take it from an option and increment it there, so that your numbering doesn't shift if you delete a post and such.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query, count" }
Show a special message for private page? If I set a page to private, can I have it show a message instead of a 404 page for public users?
This is challenging, because showing _something_ would require page not to be private. It is more common to leave page public, but make it produce conditional output depending on if user is logged (`is_user_logged_in()`) in or other criteria.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugins, pages, 404 error, private" }
How to re-enable the links manager? There is no links manager in the admin_menu of Wordpress 3.5.1 anymore. I'm creating a custom add_links_page, and I'm having a hard time with the making a plugin. Do I need to initialize something to show the links page?
It's commonly activated through: add_filter( 'pre_option_link_manager_enabled', '__return_true' ); The suggested `Link Manager` plugin only contains this code line.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 7, "tags": "links, admin menu" }
SQL Query to select post title & post ID from a particular category I am looking for SQL query to select post title & post ID from a particular category. I looked at wordpress table structure but it is really confusing me.
You can use $args = array( 'post_type' => 'post' ,'posts_per_page' => 10, 'category_name' => 'orange' ); $query = new WP_Query( $args ); printf( '<h2>Generated SQL:</h2><pre>%s</pre>', $query->request ); to display the generated `SQL` query. The above example will give you: <h2>Generated SQL:</h2> <pre> SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (123) ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10 </pre>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wpdb, sql" }
WP Redirect is not working I am trying to redirect to another URL using this code-- $siteurl= get_site_url(); //echo " This is basic property search.... now redirecting"; //echo "\n\n Redirect URL for property posts=" + $redirecturl; wp_redirect( " . $siteurl . "?post_type=property&search_keyword=" + $search_keyword . "&submit=Search" . "&price-min=" . $price_min . "&price-max=" . $price_max . "&city=" . $address_city . "&state=" . $address_state . "&zip=" . $address_zip . "&beds=" . $beds . "&baths=" . $baths); But this is where the redirection is happening-- What am I doing wrong here? Why is the correct URL not being used for redirection?
You're using a `+` sign for the first instance of string concatenation. Using a `.` instead should fix it. Additionally, WordPress provides some useful functions that might make this code easier: wp_redirect( add_query_arg( array( 'post_type' => 'property', 'search_keyword' => $search_keyword, 'submit' => 'Search', 'price-min' => $price_min, 'price-max' => $price_max, 'city' => $address_city, 'state' => $address_state, 'zip' => $address_zip, 'beds' => $beds, 'baths' => $baths, ), site_url() ) ); `add_query_arg()` allows you to build a URL with new query arguments, instead of using messy string concatenation.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp redirect" }
do_shortcode within a shortcode This may sound a little confusing but I'll try my best to explain. I've made a shortcode that grabs the content of a post (when given the id), it looks like this: $post_id = $id; $queried_post = get_post($post_id); $postcontent = $queried_post->post_content; $title = $queried_post->post_title; I then have another variable which puts a few things together and gets returned: $finaloutput = $title . $postcontent; What I want to do is be able to run shortcodes withing `$postcontent`, so when a post is fetched any shortcodes within that post will display. I tried running `do_shortcode` on the `$postcontent` variable but it caused the page to literally not load at all. Any ideas?
You can try this: add_shortcode( 'content','content_callback' ); function content_callback( $atts, $content = NULL ){ $atts = shortcode_atts(array( 'pid' => '', ), $atts); if( ! is_int( 1 * $atts['pid'] ) ) return "<!-- Shortcode Error: pid must be an integer -->"; if( absint( $atts['pid'] ) === get_the_ID() ) return "<!-- Shortcode Error: pid can't be the current id -->"; $queried_post = get_post( absint( $atts['pid'] ) ); if( ! is_object( $queried_post ) ) return "<!-- Shortcode Error: Post not found! -->"; $postcontent = do_shortcode( $queried_post->post_content ); $title = $queried_post->post_title; $finaloutput = $title . $postcontent; return $finaloutput; } where the shortcode is used like this: [content pid="2069"] where `pid` is some post ID.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode" }
How to check what plugins used to be on a WordPress installation? It's easy to see what plugins are currently disabled through `/wp-admin` — but how could I see what plugins _used_ to be on an installation of WordPress and were deleted?
You can’t. WordPress tracks the recently active plugins for a while, but there is no history of deleted plugins. You could install a logger and track this information in a special place for the future.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, customization, uninstallation, installation" }
fetch_feed showing only first item I'm trying to import a feed from a WordPress site to another using `fetch_feed()`. All is good except for the fact I can get only the first item of the feed. ## Here's the code I'm using add_shortcode('custom_feed','feed2'); function feed2(){ $rss = fetch_feed( ' ); $rss_items = $rss->get_items( 0, 3 ); foreach ( $rss_items as $item) { $title = $item->get_title(); return $title; } } Hope can help me out. This thing is driving me crazy!
It looks like the problem is from this line `return $title;` inside the `foreach` loop. Try something like this instead: add_shortcode('custom_feed','feed2'); function feed2(){ $rss = fetch_feed( ' ); $rss_items = $rss->get_items( 0, 3 ); $out = array(); foreach ( $rss_items as $item) { $out[] = $item->get_title(); } return join( ' ', $out ); } using only a single `return` after the loop. From the PHP manual on `return` : > If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. You can read more about it here.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rss, feed" }
Array of user ids to list of user names I'm outputting an array of user ids from metadata like so: `$awaygoalby = unserialize($post_meta_data['report_away-scorers'][0]);` and I want to change each user id to the user name. So I was hoping to do something like this: foreach($awaygoalby as $string){ $name = get_userdata( $string ); echo $name; } Unfortunately I get an error saying that the "Object of class WP_User could not be converted to string." What is the best way of doing this?
`get_userdata()` \- < \- returns an object. You need to provide the correct return value: echo $name->nicename;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta, array, user meta" }
How Can I Query a Specific Page From a MultiPage paginated Post Let's say I have a post that has been paginated by adding the <!-- nextpage --> code provided by wordpress for this purpose. How can I then query a specific page from inside of that post. Say for instance I only want to query the contents of page 2 and there are 10 posts. Is there a way to do it?
> WordPress uses the PHP explode function to split the content into a array of 'pages'. Happens in the setup_postdata function with this code: > > $pages = explode('', $content); source So you could do something like : function wpse_103026( $content, $pagenum ) { if ( strpos( $content, '<!--nextpage-->' ) ) { $pages = explode('<!--nextpage-->', $content); return isset ( $pages[$pagenum-1] ) ? trim( $pages[$pagenum-1] ) : $content; } else { return false; } } And then you can retrieve content of page 4 with : echo apply_filters( 'the_content', wpse_103026( $post->post_content, 4 ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, query" }
Control verbosity level of WP DEBUG? I've been at a loss so far and so I thought I'd pose the question: Is there a way to modify the verbosity level of the WP `debug.log` via `wp-config.php` or elsewhere? Just an fyi, here is what I have in my `wp-config.php` to enable logging: /////////////////////////////////////////////////// // DEBUG // Enable WP_DEBUG mode define('WP_DEBUG', true); // Enable Debug logging to the /wp-content/debug.log file define('WP_DEBUG_LOG', true); // Disable display of errors and warnings define('WP_DEBUG_DISPLAY', false); @ini_set('display_errors',0); // Use dev versions of core JS and CSS files (only needed if you are modifying these core files) define('SCRIPT_DEBUG', true); // END DEBUG /////////////////////////////////////////////////
When `WP_DEBUG` is set, WordPress sets (via `wp_debug_mode()` call early in core load process) the error reporting level to `E_ALL & ~E_DEPRECATED & ~E_STRICT`. This means all warnings and errors except strict errors and PHP deprecated functions (not WordPress ones). You can define your own level in a custom mu-plugin (the override needs to be called as soon as possible, but after WordPress core load). Use this page for information about the error levels you can use. An example: error_reporting( E_ERROR | E_WARNING | E_PARSE );
stackexchange-wordpress
{ "answer_score": 7, "question_score": 14, "tags": "debug, wp config, configuration, wp debug, logging" }
Adding querystring variable breaks admin URLs I've set up some admin pages using add_sub_menu() and whenever I add an additional querystring variable beyond the "page=" portion of the URL, I get a "Cannot load 'page-slug'." message. When I remove the every variable the page loads correctly. Here is my add menu code: add_submenu_page( 'plugin-slug', __( 'Post Types - Add', 'plugin-slug' ), null, 'manage_options', 'plugin-slug-posttypes-add', 'display_admin_page_posttype_add' ); If I browse to: /wp-admin/admin.php?page=plugin-slug-posttypes-add it works fine. But browsing to: /wp-admin/admin.php?page=plugin-slug-posttypes-add&post_type=sampletype returns: Cannot load content-toolkit-posttypes-add.
You're recieving this error because WordPress notices the `post_type` query argument and that `sampletype` is a valid registered post type, and thinks you're on an edit page. Try using a different query arg then `post_type`. Note that `admin.php?page=plugin-slug-posttypes-add&post_type=thisisnotaposttype` and `admin.php?page=plugin-slug-posttypes-add&foo=bar` will both work fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, add submenu page" }
How to add excerpt in loop in Twenty Eleven theme? Here is my loop code located in `index.php` file. I am using Twenty Eleven theme. <?php if ( have_posts() ) : ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile; ?> <?php twentytwelve_content_nav( 'nav-below' ); ?> Where should I add the `the_excerpt()` or any excerpt code into this? Content code from my content.php <div class="entry-content"> <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'twentytwelve' ), 'after' => '</div>' ) ); ?> </div><!-- .entry-content -->
Twenty Eleven uses already a conditional statement in **_content.php_** to show the excerpt in search results - <?php if ( is_search() ) : // Only display Excerpts for Search ? edit this conditional to include the other templates where you want to show the excerpt; example: <?php if ( is_search() || is_home() || is_archive() ) : // Only display Excerpts for Search, Posts Page and Archives ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, excerpt, theme twenty twelve" }
Animate.CSS with a child theme I am trying to implement animate.css with my Twenty Twelve child theme. I read this post about trying to implement it (option 1), but it is not working. The only thing I am doing differently is that I have a child theme. Any thoughts? Thanks a lot! **Edit:** Milo, you're first answer did not work. This is my code in my child theme's function.php: function paukai_2011_styles() { wp_register_style( 'animate-css', get_stylesheet_directory_uri() . ' array(), '20120725', 'screen' ); wp_enqueue_style( 'animate-css' ); } And here is my html: <p class="animated wobble">This is dummy text</p> No luck unfortunately.
The example in the page you linked uses `get_template_directory_uri()`, which will only give you the parent theme URI. If you want to target something in a child theme, you have to swap that for `get_stylesheet_directory_uri()`, which will give you the child theme URI, in the event a child theme is being used.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, theme twenty twelve" }
meta_value and meta_key filtering returning no posts this might sound like a very stupid question, and I am almost ashamed to put it here... however, after using the code straight from wp codex, and trying a couple of other variations from googling around, i simply have NO IDEA why this is not working! here's what i am using for the wp query on the index.php $args = array( 'post_type' => array('photographs', 'published_works'), 'meta_key' => 'place', 'meta_value' => 'usa', 'posts_per_page' => '-1' ); i set up a custom taxonomy called 'place', and 'usa' is one of the terms. i can get to the archive page easily, but if i want to filter it out in the index page, it simply shows no posts at all. so, i am assuming that the mistake is probably elsewhere, since the code above is taken straight from codex. any ideas of what i might be doing wrong??? much appreciated!
Taxonomies and meta data (Custom Fields) are two different things. If you want to filter on a taxonomy term, you want a `tax_query`, not a meta query.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, wp query, meta value" }
Get post only from 'standard' post format I use the following codes to get posts **only** from ' **image** ' post format and it works. <?php if( has_post_format('image')){ ?> <?php the_post_thumbnail(); ?> <?php } ?> I also need to get posts **only** from ' **standard** ' post format with the following codes, but it get post from all post formats. <?php if( has_post_format('standard')){ ?> <a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a> <?php } ?> Any solutions?
Do, <?php if( false == get_post_format() ){ ?> <a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a> <?php } ?> The standard post format isn't actually a post format, so if you conditionally check whether a post contains a post format (other than the default standard), it will return `false`, because it's set to... _standard_.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "posts, post formats" }
website is viewing as mobile, how do I turn this off? I have just changed servers from a slow server to a faster server, and I notice that my website is now automatically showing as mobile view? This has not happened before. How do I turn this off or switch it back to normal website view? I'm working in wordpress - theme: Emporium My website is: www.atadesigns.com Thank you for your help Annette
The website is working perfectly fine for me. You are using a responsive website, this means that the appearance of the site changes depending on how big your screen or browser window is. You probably had a too small browser window, if you just make it bigger it should look normal again.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "mobile" }
Cron Job variable not accessible I am currently running a cron job on my cPanel to update a variable containing exchange rates, how can I make this variable available to functions and pages in my wordpress site? **My command in cPanel for cron job running every minute:** php -q /home/username/public_html/cronjob.php **cronjob.php** <?php require('wp-blog-header.php'); $exchangeRates = getExchangeRates(); function getExchangeRates(){ // etc etc }
First of all, it's best not to include `wp-blog-header.php`. Instead, set the cron job to your homepage URL with a `?mycustomcron=true` variable appended (eg: ` Then we will check for the existance of this variable when the page loads: function wpse_103127_check_cron() { if ( isset( $_GET['mycustomcron'] ) ) { // things to do on cron here exit; // no need to load the page on cron } } add_action( 'template_redirect', 'wpse_103127_check_cron' ); As for saving the data for later access in WordPress, you can save the data to the `wp_options` table: $exchange_rates = getExchangeRates(); update_option( 'exchange_rates', $exchange_rates ); And then access it later: $exchange_rates = get_option( 'exchange_rates' ); See the Options API Codex article for more information about saving data to the database.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "variables, cron" }
Adding Menu Items in Custom Post Types I'm creating a directory of restaurants with Custom Post Types. Each restaurant's information has its own post. I would like to be able to add the restaurant's menu items to each custom post type and I'm curious how I would achieve this. I would need to make a number of fields which contain information about each menu item - the name, price, and description. I would also need the ability to click a button that says "Add another" which would then produce another row of these fields so the user can add another menu item. I'd be very appreciative if anybody knew how to do this or had a link to a tutorial.
Check out this tutorial- Adding Custom Fields to a Custom Post Type, the Right Way, it may help you out :) <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
get_the_title outputs title until spacing; it does not get full length of title If I have a post with a spacing in it (like: Hello World), than `get_the_title` shows me only "Hello" as a link and not the whole permalink. I already tried using a `substring` to get it done, but it did not work out for me. Am I missing here something? I just used `get_the_title();` and put it in a variable. Code: <?php $titletest = get_the_title(); echo " <a href= "; ?>
Your title isn't correctly encoded for use in a query variable. Try this: echo ' <a href=" . urlencode($titletest) . '">' . $titletest . '</a>';
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "query posts, get posts, title, get the title" }
Display custom taxonomy on my custom post type Hello I am very new at customizing themes, my problem is that on my new post type "listing" `single-lisiting.php` file I need to change the taxonomy category to be display to 4 new taxonomies: status, location, type, bedroom. The code I have is: <span class="itemCategory"><span class="icon-folder-close"></span> <?php echo __( 'Published in ', THEMENAME );?></span><?php the_category(", "); ?> Do not know how to change it, could someone help me.
If you're using a custom taxonomy, you can't use `the_category()` \-- that's reserved for the default WordPress `category` taxonomy. Instead use `the_terms()`: <span class="itemCategory"> <span class="icon-folder-close"></span> <?php echo __( 'Published in ', THEMENAME );?> </span> <?php the_terms( $post->ID, 'status', '', ", ", '' ); should output the `status` taxonomy for your post. ### Reference * `the_terms()` * Taxonomies
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, custom taxonomy" }
Cannot upload featured image to a custom post type For some reason I am not able to upload images OR set the Featured Image on a custom post type in my custom wordpress theme. I have added theme support of post-thumbnails to my functions.php file and my custom post type supports it. The link to add the featured image works and it allows me to start uploading the file. But before the file can complete it gives me the error message "An error occurred in the upload. Please try again later". If I visit the media library directly, the file is there, but it shows an error in the custom post page. Also, when I open the media library from the custom post page it shows as empty. Anyone out there have any thoughts on why this is?
I found the answer. I was using a function to set the thumbnail sizes incorrectly. After I changed that function to the correct format it suddenly started working again.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, uploads, post thumbnails, media library, thumbnails" }
search page different results I have custom post types and would like to display the different results based upon a users search meta. I have three custom post types that are styled differently and want to return the search results based upon their respective styles, not the generic page link and excerpt that it currently shows. could I use is_search()? <?php if ( is_search() ) : // Only display Excerpts for Search ?> <div class="entry-summary"> <?php the_excerpt(); ?> </div><!-- .entry-summary --> <?php else : ?> <div class="entry-content"> <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'bsq' ) ); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'bsq' ), 'after' => '</div>', ) ); ?> </div><!-- .entry-content --> <?php endif; ?>
is_search() is going to return TRUE on every search you perform, so that won't do what you need if I understand correctly. You'll have to use a post_type conditional tag. But it shouldn't be too difficult with something like if (is_search()) { if (get_post_type() == 'type_1') { //Do the right styling } else if (get_post_type() == 'type_2') { //Do different styling }//endif }//endif etc etc Hopefully that's what you're looking for.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, search" }
limit post by a taxonomy in the admin I have a site with authors from different locations. I have created a taxonomy called locations and has different countries (ex. Canada, Germany). Each author need only to see his country's post for the admin. For example, the author of Canada only can see and edit the post of Canada. Its is just for the admin, not the frontend. Authors should never ever be able to see any other posts. It is possible to limit posts by taxonomy in the admin? thanks!
the solution: function parse_query_useronly( $wp_query ) { if ( is_admin() && strpos( $_SERVER['REQUEST_URI'], '/wp-admin/edit.php' ) !== false ){ $wp_query->set( "location", get_user_role_location()); } } add_filter('parse_query', 'parse_query_useronly' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom taxonomy, wp admin, author" }
Add tags to custom post type without menu link I've worked out how to add tags to custom post types using `'taxonomies' => array('post_tag')` However this adds another "Tags" submenu under my custom post type menu which I do not want. How do I remove this submenu? !enter image description here
To remove the submenu _Tags_ link from the admin menu, you might try add_action( 'admin_menu', 'custom_admin_menu' ); function custom_admin_menu() { // debug to find the correct submenu slug: // global $submenu; // print_r($submenu); $menu_slug = 'edit.php?post_type=infographics'; $submenu_slug = 'edit-tags.php?taxonomy=post_tag&amp;post_type=infographics'; remove_submenu_page( $menu_slug, $submenu_slug ); } if your custom post type is _infograhpics_. By viewing the global `$submenu` array you can find the correct menu slugs.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, taxonomy" }
Customizing the display of custom post types Currently I have a custom post type and I would like to have some different version of it based on user input - so for example when creating a post the user can select if the post is Featured or Free and then there would be an if-else statement that would display different image if Featured and different if Free in the actual post. Can anyone point me to the right direction? Any advice greatly appreciated.
This sounds quite a bit like the Advanced Custom Fields flexible content field. Basically it works by letting you setup a number of different templates for how you might want to create/display your page. Then when you are in the editor, you pick which template you want to use. More info here: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field" }
how to automatically generate hierarchical menus from hierarchy of pages? I have a photo site, and I take care to crested a logical nested hierarchy of pages. e.g. for photos I just posted, I created the following pages: site.com/2013/ site.com/2013/colorado/ site.com/2013/colorado/crested-butte/ the last of these is the one on which I placed my photos. I want hierarchical menus that are easy to navigate/browse. How do I instruct Wordpress to automatically generate this?
The `wp_list_pages()` function will generate a hierarchical list of pages for you.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "menus, navigation, sub menu, hierarchical, breadcrumb" }
How can I exclude a dynamic URL to show a popup created using 'Wordpress Popup' plugin That might be a long shot, but I though I should give it a chance. I am using WordPress Popup in order to show a popup when a user lands on specific pages on the website. You create a popup and you can exclude it from showing up on specific URLs. I have a Deals website and I don't want the popup to show on cart's page. The problem I'm facing is that the page has a dynamic URL and it looks like this: '< I have tried the following ways to write it down: 1. < 2. < 3. < 4. < 5. < Any ideas on how I can handle this? Thanks in advance for any help! I'm desperated here! :) Kat
Within the javascript file the developer calls a method when the page loads. jQuery(window).load(po_selectiveLoad); This methods calls another method. function po_selectiveLoad() { po_load_popover(); } If you replace it with this function po_selectiveLoad() { var urlString = new String(window.location.href); if (!urlString.match(/\/cart\//)) { po_load_popover(); } } Of course this is not good because you will need to modify the plugin files. I am not sure if the developer has provided the option of preventing a pop up based on a phrase or word contained within the url, i installed the plugin and did not see an option. It may be a feature of the plugin the developer will implement at a later date or you can ask. Hope this helps.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, php, html" }
IOS home screen icons: where put and what size? I've read several articles about customizing the home screen icon used by IOS (and some Android) phones/tablets for the "add to homescreen" option. I'm seeing different recommendations re: sizes of the pngs, number of pngs, and am not clear where I should upload it/them. Here's a sample of articles; some WP specific, some not: < < < I like the idea of using one "large" icon and having the devices scale it, but does that work? If so, does it really need to be 512 x 512? That seems pretty big and large pngs are large files. And where do I place the pngs? In the theme root? In the media library? In the images folder in the theme root? Do I need to add anything to the code like <* _img src="/_ *images/apple-touch-icon.png"> Has anyone done this for a Wordpress theme? Thanks!
I figured out that the images needed to be in the directory where the "core" wp folders are, ie. the public_html, or in whatever sub-directory that contains the wp-admin, wp-includes, wp-content, etc. I had been placing them in the theme root and nothing was happening. Moved them to the public_html and they started showing up! In this case I was following the directions in the second article listed above: Quick Tip: Custom IOS Homescreen icons...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "ios" }
div having different appearances in different themes I have a shortcode in a plugin that is supposed to display a div. The div can be styled in the settings. The problem is: the div has different appearance in different themes. This obvious is caused by other themes modifying the styles in a generic way that I am not specifically handling. What is the _optimal_ solution such that its appearance remains same through out themes. One obvious one is to override **ALL** possible css properties in the my div related styles. Is there a better way to do that?
You need to be specific when defining your CSS styles so that a theme will not overwrite your intended style. When outputting your markup, perhaps you should even consider wrapping your div element within another div element and assuming this is the only markup on the page, you can specify them both with an #ID selector as opposed to a class selector, then in your CSS styling: div#myPlugin div#innerWrap { background: black /* etc */ } ...and so on. That is going to be pretty hard to overwrite as you are being far more specific than what a theme could possibly ever be without the theme knowing the exact div ID names ahead of time, **_which they wont_**. You could also inject your styles inline which will take top precedence over all other defined styles, <div id="myPlugin"> <div id="innerWrap" style="background:black"> content </div> </div> **Inline wins!**
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, shortcode, css" }
What happens when wp_cron is deactivated in Wordpress? In a Wordpress 3.5.1 the apache log generates the following error related to wp-cron.php: > [18/Jun/2013:10:53:21 +0200] "POST /wp-cron.php?doing_wp_cron=1371545601.7393701076507568359375 HTTP/1.0" 200 211 "-" "WordPress/3.5.1; < [18/Jun/2013:10:54:36 +0200] "POST /wp-cron.php?doing_wp_cron=1371545676.3652250766754150390625 HTTP/1.0" 200 211 "-" "WordPress/3.5.1; < [18/Jun/2013:10:56:44 +0200] "POST /wp-cron.php?doing_wp_cron=1371545804.4974770545959472656250 HTTP/1.0" 200 211 "-" "WordPress/3.5.1; < > > ... More than 700 petitions per hour like this are made and I do not have any Cron plugin. I think if I insert the following code in wp-config.php it will desactivate this cron: define('DISABLE_WP_CRON', true); I would like to confirm this and ask about what possible pernicious secondary effects this could have.
`wp_cron` is used to schedule tasks such as deleting old posts from trash, deleting old spam comments, and checking for plugin/theme updates.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "plugins, cron, wp cron, apache" }
Removing buttons from the editor I have this nice little function to remove buttons from the tinyMCE editor in WordPress, so far I've been able to remove most of the ones I need to. function custom_disable_mce_buttons( $opt ) { $opt['theme_advanced_disable'] = 'justifyfull,forecolor,removeformat,justifycenter,justifyright,justifyleft,charmap,indent,outdent,undo, redo'; return $opt; } add_filter('tiny_mce_before_init', 'custom_disable_mce_buttons'); The button control list can be found here: < The problem is, there's a few more ones I'd like to remove, like the spellchecker and the 'insert more tag', but I can't find documentation anywhere of the codes/names for these buttons to remove them. Any got any info on this?
`wp_more` \- insert more button, `spellchecker` \- spellchecker button I've tried it with your code on WP 3.5.1 and it worked fine for me.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 8, "tags": "tinymce" }
Wordpress Feed Creator Name Tag Full Name Instead Of First Name I am parsing a Wordpress feed in my iOS application. I don't know much about Wordpress and its customisation. The feed shows the author name as below: <dc:creator>andy</dc:creator> while i want it to show the full name of the author in the feed like: <dc:creator>andy rubin</dc:creator> Can anybody point out where I can go to do that. Thanks!
You can change the `dc:creator` author names by visiting the the user profile settings and change the display name: !enter image description here where you have filled out the first/last name text fields.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development" }
Combine two conditions in one statement syntax I have two queries that I would like to combine because it becomes a lot of code and I think that's not necessary but I make a mistake with the syntax I want to combine } elseif (is_category( 'latest-news' )) { With } elseif ( is_single() && in_category('latest-news')) { I tried elseif (is_category( 'latest-news' )) || ( is_single() && in_category('latest-news')) { and elseif (is_category( 'latest-news' )) or ( is_single() && in_category('latest-news')) { but they both don't work, probably I am doing something wrong. How could I combine these two?
It looks like you got an extra `)` and one missing `)`, try this: elseif( is_category( 'latest-news' ) || ( is_single() && in_category( 'latest-news' ) ) ) { ps: You should also post any PHP error you get.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "customization, filters" }
Post sharing in social network I have a problem. There is AFTER SINGULAR in widgets line. Then I chose widget: text or HTML code. I have a pictures of 3 social media icons (facebook, twitter, pinterest) I want that icons (facebook, twitter, pinterest) link will be to : Example: < < I want that there would be automatic write post title and post URL. So, what should I write in the end of the link? (facebook, twitter, pinterest) Please, help. :-)
Text widget is only static text widget. You need to place link to current post on the end of the sharing link (and you have to urlencode it), so I don't think that text widget will help you with your problem. The easiest solution to your problem will be adding these sharing links in your themes .php file (if you want to place them in sidebar, then sidebar.php would be appropriate file - but it may depend on your theme structure).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "social sharing, sharing" }