INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
What's wrong with my use of plugin_url()? I keep getting the following message in the browser `Fatal error: Call to undefined function plugin_url() in` My code at present: add_action( 'wp_enqueue_script', 'load_jquery2' ); function load_jquery2() { wp_enqueue_script( 'jquery' ); } function add_my_css_and_my_js_files(){ wp_enqueue_script('jquery-validate-min', plugin_url('/activate/jquery_validate_min.js', __FILE__ ) ); } add_action('wp_enqueue_scripts', "add_my_css_and_my_js_files"); The plugin is in a folder called 'activate' & the JS is in that folder directly, not a sub folder.
function add_my_css_and_my_js_files(){ wp_enqueue_script('jquery-validate-min', plugins_url('activate/jquery_validate_min.js', __FILE__ ) ); } add_action('wp_enqueue_scripts', "add_my_css_and_my_js_files"); 1. You need to use the `plugins_url()` function (you are missing the **s** at the end of _plugins_ ). 2. Reference the location of the script file with the relative path. Meaning the path should be `activate/jquery_validate_min.js`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, plugins url" }
Problem with multiple menus in theme I am having trouble trying to get my new theme working. I have all 4 menus working on my test server but when I move the theme to the live server and set up all but one (main-menu) will not show up. Here is my code for the menus: register_nav_menus( array( 'main-menu' => __( 'Main Menu', 'Bootstrap WP Primary' ), 'second-menu' => __( 'Second Menu' ), 'footer-menu' => __( 'Footer Menu' ), 'mobile-menu' => __( 'Mobile Menu', 'Mobile Menu' ) )); Here is the code from the current template: register_nav_menus( array( 'main-nav' => __( 'Main Nav' ), )); Is it a conflict with the main menu items? !white Menu is Second Menu, Purple is Main !white Menu is Second Menu, Purple is Main and isn't showing up on live site Also upon inspection of the code the menu isn't even being populated on to the page.
To display a menu you need to use the `wp_nav_menu` function (Codex reference). Try changing your template file to use the following code: <?php wp_nav_menu( array( 'theme_location' => 'main-menu' ) ); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, menus, templates" }
Activating a Theme Options page to Editor - not working I used Ian Stewart's Simple WordPress Theme Options Page (Source^) for my client's site, where I assigned my client as an Editor. But from the Editor account the **Theme Options** link is not visible. I checked the `theme-options.php` for `add_theme_page()`, where it's used `'edit_theme_options'` as the menu's capability. But unfortunately it's not visible. I installed: * User Role Editor, and * White Label CMS But in White Label CMS, I unchecked the hide menu thing. But the link becomes visible only if I check the User Role Editor's `manage_options` checkbox. But it opens the Settings menu to the Editor. I checked the `edit_theme_options` for Editor, but it doesn't work. I changed the `theme-options.php`'s `add_theme_page()` capability to even lower to `edit_published_posts` (Author capability), but not worked here. I tried deactivating User Role Editor, but no luck.
Ok. Found the guilty one: it's **White Label CMS**. !White Label CMS Activating only the **Site Options** did not working, when activated the **Menus** too, it's working.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme options, editor" }
Create a wordpress admin user and only let them edit and post blog posts? Is it possible to create a WordPress admin user and only let them edit and post blog posts?
By "admin user" I'm guessing you mean someone who can log into the backend. If so, yes, you can go to Users > Add New in the backend, and create a user with the "Role" dropdown set to "Author". !Adding an "author" user. This person will be able to delete, edit, and publish posts, as well as upload files (e.g. pictures). See < for more information. If you need a user role with more limited capabilities (e.g. can only edit and publish posts, can't delete them), use a plugin like < to edit the user roles.
stackexchange-wordpress
{ "answer_score": 3, "question_score": -2, "tags": "users" }
How can I safely delete data related to wp_post table manually from the mysql database? Recently I downloaded a plugin that had a bug that orphaned its custom post type items in the wp_post table rather than deleting them. Being new to wordpress, it wasn't apparent to me that the wp_postmeta table was related to that table. Now, I have entries in the latter with NULL values for the $post_id. (I simply deleted everything in wp_post with that content type.) I'm assuming that it would be easy enough to do a left join query to find all those wp_postmeta items and delete everything with $post_id NULL. But, I'm not exactly sure how the wordpress tables relate to each other. If I were to do this manually, are there any other default tables that need to be taken into consideration? Does anyone have a script in their library to handle something like this? If you can suggest a plugin, I'm open to that as well.
As you already deleted all the posts in the table, this is going to be quite a bit of work manually. For the next time you do something like that, use `wp_delete_post( $postid, $force_delete );` (Codex) while looping through all the posts with that posttype, as this function deletes all the data associated with that post. $args = array( 'posttype' => 'yourposttype', 'numberposts' => -1 ); $todelete = get_posts( $args ); foreach( $todelete as $deletethis ) { wp_delete_post( $deletethis->ID, true ); } In your case, you will have to check the following tables for data (I skip the tableprefix here): * posts (which you already did) * postmeta * comments/commentmeta * term_relationships In all cases you will have to search for entries with the `post_id`/`object_id` NULL or with no entry in the posts table, and delete them. The SQL should be pretty straight forward.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database" }
Check if user is logged in else login page I like to secure a certain page for admins. How do I check if a user is logged (and is admin)? Of their not logged in, I want to show the login module.
if(!current_user_can('administrator')) { wp_redirect( wp_login_url() ); } This will redirect non-admins to login URL. Of course, logged in non-admins will be a bit confused. You'll want to run this before `get_header()`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "admin, wp login form" }
how redirect users to custom login page when "login to reply" is clicked? I am building my website on Wordpress and I have created my custom login page.But for a post when an user comments and other nonlogged see the comment with along with a line down "Login to reply".And when the user clicks on that"Login" from "Login to reply" it redirects to wp-login.php.So how to redirect users to custom login page when "login to reply" for a post is clicked on wordpress instead of wp-login.php.
You need to redirect everytime WordPress looks for `wp-login.php`. You can do the same by using the below in your active theme's **`functions.php`** file. function redirect_login_page(){ // Store for checking if this page equals wp-login.php $page_viewed = basename( $_SERVER['REQUEST_URI'] ); // permalink to the custom login page $login_page = get_permalink( 'CUSTOM_LOGIN_PAGE_ID' ); if( $page_viewed == "wp-login.php" ) { wp_redirect( $login_page ); exit(); } } add_action( 'init','redirect_login_page' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users, redirect, login" }
Custom category for posts via XMLRPC I have a blog located at one site that when I post into a category, it will auto-post via XMLRPC to another site of mine. This functionality works, but I would like to assign a category to these posts. Is there any way to do this? The only site that will be posting this way is controlled by me, so I don't care if it's global. Thanks
You can do it by sending the 5th parameter to wp.newPost, like this: $request = xmlrpc_encode_request( "wp.newPost", array( 1, $xmlrpc_username, $xmlrpc_password, $content, $terms) ); Please note the **$terms** should be in this format: **'Taxonomy names as keys, array of term IDs as values'** , according to the Codex. FYI, here is another thread related to your question.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, xml rpc" }
Min height of page I am using the Weaver theme and would like to set the minimum page height to a certain size. I have read about it and added: min-height: 900; to my style sheet but it does not seem to be working. What should I do?
You should set `min-height` to **900px** instead of just **900**. 900 might work in some browsers, but probably not in yours.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -3, "tags": "css" }
Custom-Metaboxes-and-Fields text_url field prepending http:// I'm using the Custom Metaboxes and Fields code wich is pretty good. However I need sanitization on URL fields of course but the built in text_url field type is adding ' to my entries. I know it is using WP's esc_url (cmb_Meta_box_types.php) And cmb_Meta_box_Sanitize esc_url_raw() How can I get this field type to return only the inputted value?
It seems that esc URL was the culprit. Even though I wanted to hard code the base URL eg. < I was esc_url'ing the input field for which to append to the base. I've switched to using a regular text field and am esc_url'ing the entire output string.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "metabox, sanitization" }
How to determine what is generating large amount of database queries? For some reason, my Wordpress site is using a lot of memory (spiking at 72MB) and generating a huge amount of database queries (76923 according to Wp-Memory-Usage. I'm really not sure why this would be, as there is nothing going on on the site that would create these. The only thing I can think of is the Ninja Forms plugin. The site is here: < And the plugins installed are: BlackStudio TinyMCE Easy Bootstrap Shortcodes Ninja Forms Shortcodes Ultimate Page Builder by SiteOrigin TPC Memory Usage WP-Pro-Quiz Plugin Performance Profiler I have a plugin load time of .449 sec per visit, Plugin impact of 58.8% of page load time, and 98 MySQL queries per visit (all according to the Plugin Performance Profiler). Any insight would be hugely appreciated.
You can use Query Monitor plugin **From Plugin Documention:** Here's an overview of what's shown: > **Database Queries** > > 1. Shows all database queries performed on the current page > 2. Shows affected rows and time for all queries > 3. Show notifications for slow queries and queries with errors > 4. Filter queries by query type (SELECT, UPDATE, DELETE, etc) > 5. Filter queries by component (WordPress core, Plugin X, Plugin Y, theme) > 6. Filter queries by calling function > 7. View aggregate query information grouped by component, calling function, and type > 8. Super advanced: Supports multiple instances of wpdb on one page > > > Filtering queries by component or calling function makes it easy to see which plugins, themes, or functions on your site are making the most (or the slowest) database queries.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, database, mysql" }
Make WooCommerce pages accessible for logged in users only I have a website using WordPress, and an e-commerce using WooCommerce. I would like my shop (and all its pages) to be seen by logged in users only. Via the _User Access Manager_ plugin, I have denied access to the shop page, but with a direct link to a product etc. one can access that particular page nonetheless, even if the user is not logged in. How can I redirect users, who are not logged in, to another page if they try to access a WooCommerce page?
Put this in your `functions.php` file: function wpse_131562_redirect() { if ( ! is_user_logged_in() && (is_woocommerce() || is_cart() || is_checkout()) ) { // feel free to customize the following line to suit your needs wp_redirect(home_url()); exit; } } add_action('template_redirect', 'wpse_131562_redirect'); **What does it do?** We check if a _not-logged-in user_ wants to see a WooCommerce page, and redirect him/her to our home page.
stackexchange-wordpress
{ "answer_score": 27, "question_score": 13, "tags": "users, woocommerce offtopic" }
Custom Query - show first post twice? In a custom query, is there a way to show the first post twice? I want to show the first post in a certain format at the top of my query, then again right under it along with my other posts (maybe a little redundant). I've tried just pulling the post then showing it like, but when I call `the_post` it seems to remove it from my overall array of objects. **Simplified Version** <?php if($test->have_posts()) : $test->the_post(); ?> <h1><?php the_title(); ?></h1> <?php endif; ?> <?php if($test->have_posts()) : ?> <?php while($test->have_posts()) : $test->the_post(); ?> <h3><?php the_title(); ?></h3> <?php endwhile; ?> <?php endif; ?> I've also tried to get into the array but I'm not sure how: $post = $test->WP_Query[0]; How can I show my post, without 2 queries or modifying the original custom query?
Just rewind posts after the first post and run the loop again. if($test->have_posts()) : $test->the_post(); the_title(); endif; $test->rewind_posts(); if($test->have_posts()) : while($test->have_posts()) : $test->the_post(); the_title(); endwhile; endif;
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "wp query" }
Get posts by list of post IDs ordered by those IDs? I am going to make a "favourite" posts box, but the article id's are stored in another DB so I only get an array of IDs (which **are** relevant to the WP DB). I think it could be done with `get_posts()` or simply just with `WP_Query`, however as I am surfing through the codex I cant find solution to my problem - you can obviously select posts by multiple tags, authors,... but I cant find something similar for just IDs. I wouldnt even mind if the posts werent ordered. Mainly I just want to get a bunch of posts in one (WP)Query providing only posts' ids. Any Ideas? Thanks :)
You could use `post__in` as a parameter in your `WP_Query`, like: $favourite_posts = new WP_Query( array( 'post__in' => array( 111, 222, 333 ), 'orderby' => 'ID' ) );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "wp query, get posts, array, id" }
How to create categories out of a list of words? I have a simple text file with a list of words (Berlin Hamburg Stuttgart ...) and so on. They are cities of germany an nearly 2000 counted. I need everyone of them as a category in my wordpress site and looking for the best way to achieve this. Is there a faster way than to create every single category manually from the dashboard? Thanks for your help!
Assuming you have a nice list of your Words, you could easily create an `array` with them, doing a little data manipulation. Afterwards you can loop throug your `$array` and insert the Term accordingly: $yourcities = file($filename, FILE_IGNORE_NEW_LINES); // all your valuesfrom the .txt file foreach( $yourcities as $thiscity ) { wp_insert_term( $thiscity, // the term, in your case the name of the city 'category', // the taxonomy, in your case category array( 'description'=> '', // if available 'slug' => '', // leave blank if not available 'parent'=> $parent_term_id // if you do it hierarchical, be sure to insert the parent ID here ) ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "php, categories" }
How to get post body look same as my visual editor? When I apply the format and styles such as bold and `<br/>` on visual editor it looks bit nicer. But when I see that on blog post it looks totally different. I do not use any styles for p tag in my style sheet. How can I just get the same look of post with styles I applied in visual editor when I see the post on the site?
the editor uses its own stylesheet which might be quite different from the one on your theme. If you are willing to dig into the code it would make sense to make a stylesheet for the editor. See this for details <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, visual editor" }
Sign in with social media accounts without creating a WP account I'd like users to sing in with their social media accounts (facebook, twitter, linkedin, google+) without creating a WP account. This is for them to be able to leave comments on a website. Is this possible and what's the best approach for this?
I have come across a WPMU Dev's plugin called Comments Plus. It doesn't create a WP user. It allows to connect with: * WordPress.com account * Twitter * Facebook * Google You can choose to disable any of this social media for signing up, however, can't add extra social media account at this point. I hope this helps someone!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "login, user access, social connect" }
how is it possible that using wp_insert_category throw a fatal error? how is it possible that using wp_insert_category throw a fatal error ? I am using it as explained : < with no change except: $cat_defaults = array( 'cat_name' => 'some_name', 'category_description' => 'as asdfasdf sdf adfa fas f', 'category_nicename' => '', 'category_parent' => '', 'taxonomy' => 'category' ); $someSome = wp_insert_category($cat_defaults); i dont know if its relevant however i execute it on `add_action( 'init', array($this, 'registerCustoms') );` And i get the following error : `Fatal error: Call to undefined function wp_insert_category() in /home1/stodeckc/public_html/podio-wp-sync/wp-content/plugins/podio_management/libs/appSync/appSync_custom.php on line 61` Any ideas?
The `init` action is the wrong place. This is because `init` runs on all requests, admin or front-end, but the `wp_insert_category` function is an admin-side only function. You generally don't insert categories from the front end. Move to a more specific action, one that will be run in the admin side. Probably from your plugin's admin pages.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "terms" }
Possible to change the slug of default post type? I have custom post types on my wordpress site and I've set the slugs to say "/blog/{post_type}/{post_title}". I'm using the default post type as a "notes" section, so I want that slug to be "/blog/notes/{post_title}". Is this possible?
There are many »default post types« like `post`, `page` or even `nav_menu_item`. If you talking about `post` as the default just go to Settings → Permalinks admin page, chose »custom structure« and use `/blog/notes/%postname%/` as your structure.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, url rewriting" }
How to get posts in different language from WPML Plugin i'm using Thermal-Api plugin in order to define a REST WS to get posts in JSON format. My Client uses WPML to translate posts and i need to pass to WP_Query the language set in front-end side. Is there a particular parameter to pass to WP_Query to select only the post in that language or is there a way to change dynamically "ICL_LANGUAGE_CODE" in order to retrieve what i need?? Thanks!!
Assuming `$new_lang` holds the desired two letter language code (e.g. 'fr'), you can do this: global $sitepress; $current_lang = $sitepress->get_current_language(); //save current language $sitepress->switch_lang($new_lang); //...run query here; if you use WP_Query or get_posts make sure you set suppress_filters=0 ... $sitepress->switch_lang($current_lang); //restore previous language For more info, check <
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "wp query, plugin wpml" }
How to hide wordpress error message? how to hide wordpress error message "You do not have sufficient permissions to access this page" and show 404 error page for all non administrator's request like e.g mydomain.com/wp-admin/plugin.php and all such requests. And they should be redirected to 404 error page.
Depends on what you mean by "redirect". If you want to 404 them, this will do the job: add_filter('wp_die_handler','custom_404_die_handler'); function custom_404_die_handler() { global $wp; $wp->handle_404(); load_template(get_404_template()); die(); } If you actually want to redirect them somewhere, then you could do something like this, but that's not exactly a "404", as such. add_filter('wp_die_handler','custom_404_die_handler'); function custom_404_die_handler() { wp_safe_redirect( get_home_url() ); die(); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permissions" }
Remove parent page from url I would like to remove the parent page name from the permalink. At the moment, I have site.com/parent-page/child-page.php and I would like to have something like that site.com/child-page.php
There's a plugin Custom Permalinks to the rescue. But you have to change the permalink page by page.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks, url rewriting, urls" }
WPDB query - decrypting DB data I am trying to grab data from the DB using WPDB but I am stuck on how to decrypt the data e.g. The data is stored as: a:2:{i:0;s:2:"92";i:1;s:2:"71";} I want the 92 & 71 as that's my post IDs, how to I get that part from the DB using WPDB? My code so far is: $crosssells = $wpdb->get_results( "SELECT * FROM $wpdb->postmeta WHERE _crosssell_ids != '' " ); The table is only created when data is in putted in the post so I need to check if the table exists and then grab the post id's
It's just serialized, in WordPress, you can run maybe_unserialize and get back the variable/array. $crosssells = $wpdb->get_results( "SELECT * FROM $wpdb->postmeta WHERE _crosssell_ids <> '' " ); $array = maybe_unserialize($crosssells); However, there are built in functions to retrieve posts based on meta information. You can use get_posts to retrieve the posts and get_post_meta to retrieve meta information from a specific post id. It's best to abstract away from direct database interaction to take advantage of the built in caching, security, etc of WordPress.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query, wpdb" }
Display current category title on category page Using the following code in a category template, but instead of showing the current category page that I am on, it displays the first category of the first post. For example on Food category page it should say Food, but instead it says Desserts because the first post's category is desserts. Here is the site < add_action ( 'genesis_before_content', 'sk_show_category_name' ); function sk_show_category_name() { $category = get_the_category(); if (is_category()) { echo '<div id="cat-name">' . $category[0]->cat_name . '</div>'; } }
On a category page, you can use the function `single_cat_title()`, or the more generic `single_term_title()`. These functions pull from the global `$wp_query` object, via `get_queried_object()`.
stackexchange-wordpress
{ "answer_score": 42, "question_score": 13, "tags": "php, categories, genesis theme framework" }
permalinks has -2 with post name structure. why? I have set permalinks structure in my website as post name, then it supposed to come as: but it is coming as: I dont know why the -2 coming with some pages ? Thanks for help... :)
Probably page-name permalink already exists.. Check it in trash as well....
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "permalinks" }
deleted menu still present I deleted a menu, but it still shows at the top of my website (About Us -to- Request Consulting Services). The site is using AppThemes.com's JobRoller theme as a parent, and the Flux child theme. There are no caching plugins installed. When I change the theme, the front end changes immediately. So why doesn't the menu change immediately after it is deleted?
The theme displays pages in the primary menu location even when there is no Wordpress menu assigned to that location. I changed the pages to Draft status to resolve this issue.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "menus" }
content summary of a post disappears If an images added at the beginning of the post. how to solve it? If I put an image at the beginning of the post my content just disappears at the home page. but when I click read more button it shows full content ( **single.php** ) **index.php** <?php if (strlen(get_the_content()) > 10) { $content = get_the_content(); echo str_replace('&nbsp;', '', substr($content, 0, 50)). "...."; ?> How can I show the content summaryon the home even I add an image at the beginning of the post? Any help will be very much appreciated....
You should probably use the core function the_excerpt() to avoid this problem. You can customize the length of your automated excerpt (see link below), so there's really no reason to use the function you've used. This problem is probably caused by the str_replace funtion in your code. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, content, excerpt" }
Function to remove all classes on images inserted into posts? I'd like my images to have no classes assigned to them by default, as I (sometimes) add my own classes to create custom 2 column layouts... can I do this without hacking the core? From my googling it looks like image_send_to_editor would work, but creating a regex for this is beyond me... <img class="alignnone size-full wp-image-5129" alt="cl_1st_birthday_2" src=" width="1152" height="768" /> to <img class="" alt="cl_1st_birthday_2" src=" width="1152" height="768" />
One liner should do it, remove all classes. add_filter( 'get_image_tag_class', '__return_empty_string' ); Filter can be found in wp-includes/media.php in the `get_image_tag` function.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images, media" }
Is it possible to remove subscription box from Jetpack stats page? Is it possible to remove following box from Jetpack's stats page as I'm using Feedburner? !Jetpack
The easiest way might be to hide it using CSS. If there's a class or id unique to the container, add this to your theme's functions.php: add_action('admin_head', 'custom_admin_css_ha'); function custom_admin_css_ha() { echo '<style> #unique-id-or.unique-class-goes-here { display: none; } </style>'; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, plugin jetpack, statistics" }
Add_meta_box not appearing, but does appear in screen options I'm adding a meta box to a WordPress admin page. It works fine on my local server but when I upload it to the live server, the meta box doesn't appear. Its does however appear in the screen options, so I know the code is working to some extent but it's just not displaying anything on the edit page. I've uninstalled all the plugins and that didn't equally solve the issue. Below is my code: function ila_add_custom_box() { add_meta_box( 'content-on-page', 'Content On Page', 'ila_render_meta_box', 'page', 'high' ); } add_action( 'add_meta_boxes', 'ila_add_custom_box' ); function ila_render_meta_box() { echo "<h1>Edit Page Options</h1>"; } How can I resolve it?
You missed one argument in the `$args` for `add_meta_box`. The correct use would be (Codex): add_meta_box( $id, $title, $callback, $post_type, $context, $priority, $callback_args ); You forgot to set the `context`, add it and you should be fine. add_meta_box( 'content-on-page', 'Content On Page', 'ila_render_meta_box', 'page', 'normal', // add this line 'high' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "metabox" }
How do I get resized thumbnails? I'm getting post thumbnails by calling `the_post_thumbnail(array(400,300), true);` However, this displays the fullsize featured image, just resized with the html "height" and "width" tags. This is not good for loading times. I've tried regenerating thumbnails and that doesn't make a difference. Isn't there a way to get thumbnails that have been resized?
Your example code is calling the full size image as you mention and resizing to the dimensions you feed into the array. I've answered this question before here, but the basic idea is that you'll want to use `add_image_size()` in your `functions.php` to tell Wordpress you'd like it to create a new image size when you upload images. Then you'll need to use `wp_get_attachment_image()` to call the image into your template.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, post thumbnails" }
WP E-commerce and Display Fancy Purchase Notifications I have enabled Display Fancy Purchase Notification for WP E-commerce but it looks like that fancy pop-up window is not working. Console throws an error > jQuery( 'form.product_form, .wpsc-add-to-cart-button-form' ).on( 'submit', function() { TypeError: jQuery(...).on is not a function but add to cart functionality works. Site is located here: < Thanks
Found that theme functions was handled `wp_deregister_script('jquery')` and jQuery loaded from one of plugins was outdated (1.5.2) which was causing all errors. I have removed `wp_deregister_script('jquery')` from the functions.php file and all working as should.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin wp e commerce" }
How to change src link in YouTube? I want to add `html5=1` in YouTube link. How can I do that? I try something like this: function add_embed_filter($html, $url, $attr) { $new = str_replace('oembed', 'oembed&html5=1', $html); return $new; } add_filter( 'embed_oembed_html', 'add_embed_filter', 50, 3 ); but in source it look like this: `?feature=oembed&#038;html5=1` :/
function add_embed_filter($html) { return '<div class="js-video widescreen">'.str_replace("?feature=oembed", "?html5=1", $html).'</div>'; } add_filter( 'embed_oembed_html', 'add_embed_filter', 50, 1); Of course if WordPress or Youtube change how this url is constructed you will have to adapt your code accordingly, but I tested it, and this will get you there with WordPress 3.8.1. I also did not test how this works for a user who does not support HTML5 and depending on your use case, you may wish to test to ensure that this code will support them.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "youtube" }
How to redirect non-logged in users to a specific page? How to redirect non-logged users requesting for a specific page/URL to another page/URL and display a message like "for members only". I know its quite easy to code using !is_user_logged_in() function but i don't know how to code it because i am a newbie to WordPress. Care to tell me the file to put the code also.
Here are 2 examples which you will need to modify slightly to get it working for your specific needs. add_action( 'admin_init', 'redirect_non_logged_users_to_specific_page' ); function redirect_non_logged_users_to_specific_page() { if ( !is_user_logged_in() && is_page('add page slug or ID here') && $_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php' ) { wp_redirect( ' ); exit; } } Put this in your child theme functions file, change the page ID or slug and the redirect url. You could also use code like this: add_action( 'template_redirect', 'redirect_to_specific_page' ); function redirect_to_specific_page() { if ( is_page('slug') && ! is_user_logged_in() ) { wp_redirect( ' 301 ); exit; } } You can add the message directly to the page or if you want to display the message for all non logged in users, add it to the code. <
stackexchange-wordpress
{ "answer_score": 42, "question_score": 24, "tags": "redirect" }
Javascript WP Object Documentation? I was working on implementing the media library within one of my plugins/themes. I found a nice tutorial (< that showed me how to do this using the JS object 'wp' I can't seem to find any documentation on this in the codex or when Googling. How does one learn this object and its methods?
< It's a work in progress. Contribute if you can!
stackexchange-wordpress
{ "answer_score": 3, "question_score": 7, "tags": "javascript, media library, documentation" }
get category name in admin screen I want to get the name of the category that I am editing posts in. So I have this code that I found here function add_custom_submenus() { global $submenu, $post; $submenu['edit.php'][] = array( __('Back'), // menu title 'edit_posts', // menu cap 'edit.php?category_name=' . $category_name // menu link ); } My link shows great. I know the page that I need to go back to. I am just having trouble finding the name of the page. The admin screen shows edit.php?category_name=band-member band-member is the name of the category that I am editing posts in. So I was trying to create a link back to the band-member posts page. I can't figure out the php to get the name of the category of the current post that I am editing.
add_action( 'admin_menu', 'add_custom_submenus', 9999 ); function add_custom_submenus() { global $submenu; if( isset($_GET['post']) && get_post($_GET['post']) && isset($_GET['action']) && 'edit' == $_GET['action'] ) $post = get_post($_GET['post']); if( isset($post) && !empty($post->post_type) && is_object_in_taxonomy($post->post_type, 'category') ){ foreach ( (array) get_the_category($post->ID) as $cat ) { if ( empty($cat->slug ) ) continue; $submenu['edit.php'][] = array( __('Back'), // menu title 'edit_posts', // menu cap 'edit.php?category_name=' . $cat->slug // menu link ); } } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
Results not being printed I am trying to run the following code, which i got from the site but i don't see any output.When i do `print_r($product)` only then i get array back. $args = array( 'post_type' => 'product', 'posts_per_page' => 4 ); $featured_query = new WP_Query( $args ); if ($featured_query->have_posts()) : while ($featured_query->have_posts()) : $featured_query->the_post(); $product = get_product( $featured_query->post->ID ); echo $product; endwhile; endif;
You're `_doing_it_wrong`, as `$product` is an object. I'm pretty sure you want something like this: $args = array( 'post_type' => 'product', 'posts_per_page' => 4, ); $featured_query = new WP_Query($args); if ($featured_query->have_posts()) { while ($featured_query->have_posts()) { $featured_query->the_post(); ?> <h1 class="post-title"><?php the_title(); ?></h1> <div class="post-content"><?php the_content(); ?></div> <?php } wp_reset_postdata(); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "woocommerce offtopic" }
How to enable qTranslate languages tabs in custom plugin page For example, I have created a custom post creator. I am using `wp_editor()` to generate "WYSIWYG" editors for content. I am using `qTranslate` for multi-language user experience. Unfortunately I am forced to create a separate "WYSIWYG" editor for every language translation. Overkill. How to enable / implement `qTranslate` language tabs as they are in default post creator.
1 - I would think that the qtranslate plugin will add the tabs to the wp_editor() editor automatically. At least , it was doing it when I used it for CPT .. 2 - there is this plugin which helps plugin authors to implement qtranslate in own plugins . 3 - there is a filter `add_filter(‘the_editor’, ‘qtrans_modifyRichEditor’);` in qtranslate you might want to investigate 4 - you can also use a simple loop in order to create the tabs using `qtrans_getLanguage()`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, posts, plugin qtranslate" }
Is there any hook for theme activation ? or something similar? I know this has been asked before however my question is different. So. I have a plugin that creates custom post types on the fly. the plugin also has a function to create template files for each of those custom post types. it simply goes to those theme folder and create template page for each of the current theme. this works perfectly for the current themes. however what happened if the admin added another theme and active it ? So i am looking for a way to detect activation and then run the function to create the template page for that theme. My first idea was to check theme activation hook which i dont think going to work. Anyone with a different idea ?
Don't save the template in the current theme. Instead, save the template in your plugin itself and try to use the template using `template_include` filter for particular page or whatever using `is_page`. By this you don't have to worry about theme change.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, themes, templates" }
Translate placeholder text in search field I want to translate the placeholder attribute in my search box. I am using the WPML-plugin to translate all text. How can I accomplish this? My code: <input type="search" class="search-field" placeholder="Your Search term here" value="<?php echo esc_attr( $search ); ?>" name="search">
Just as any regular string, you can use <?php esc_attr_e( 'Your Search term here', 'your_theme_slug' ); ?> So your code for the `<input>` would look like <input type="search" class="search-field" placeholder="<?php esc_attr_e( 'Your Search term here', 'your_theme_slug' ); ?>" value="<?php echo esc_attr( $search ); ?>" name="s"> WPML, as well as WordPress, uses the PHP `get_text()` function. You can translate this either with the additional String Translation Plugin, or you create a mo/po file for your theme.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multi language, translation, plugin wpml" }
How to place HTML below the title of the (custom) post overview **Edit:** Yes, I know, I provided an answer to this question myself. However, I'm still interested in other solutions and/or comments on the one I found. Is this how you would do this? Are there any other ways? * * * I would like to provide some additional description and on-page help (i.e., no contextual help or help tabs) on the overview page (i.e., `edit.php`) for a custom post type. According to `edit.php` (as well as `class-wp-list-table.php` and `class-wp-posts-list-table.php`) there is no appropriate hook. So, how can I do this? A few notes: * I came up with a solution, which I would describe _a bit hackish_ , so I'm open for a _clean_ solution (if there is one); * I will post my solution as an answer so you can comment on that (and so the question and answer are kept separate); * I'm aware that I can do this via JavaScript/jQuery - but that's not _clean_ (IMO) as well...
I kind of feel like I'm missing something obvious, but maybe I'm not. What about the `admin_notices` hook, seems like the obvious choice to me. There are some admin CSS classes available you can use, like `updated`, `error` or `update-nag`, or you can of course add your own styles, like asked and answered here or here. **Code:** <?php function my_cpt_info() { if ('edit-my_cpt' === get_current_screen()->id) { ?> <div class="updated"> <p> <?php _e('Some information about my CPT...', 'my-text-domain'); ?> </p> </div> <?php } } // function my_cpt_info add_action('admin_notices', 'my_cpt_info'); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "posts, customization, wp admin, hooks" }
meta_query dates from an array I have the below query which isn't returning anything. The query is meant to look for the date (2014-03-01) that is in the array, which it is. Any ideas? Or would I need to use a custom SQL query? // the income_dates array looks like this // a:3:{i:0;s:10:"2014-02-01";i:1;s:10:"2014-03-01";i:2;s:10:"2014-03-29";} $args = array( 'post_type' => 'income', 'meta_query' => array( array( 'key' => 'income_dates', 'value' => "2014-02-01", 'type' => 'date', 'compare' => 'IN' ), ) );
If you store the meta as a serialized array, you should do meta query like this: $args = array( 'post_type' => 'income', 'meta_query' => array( array( 'key' => 'income_dates', 'value' => "2014-02-01", 'compare' => 'LIKE' ), ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, loop, query, mysql" }
Display all sub category but one How would I display all the sub category but one? I tried `is_category('myslug')` then return in the post loop but it wont work. my code in the post loop if(is_category('myslug')){ return; } Stills return all the sub category even the one with slug `myslug`
If you'd like to exclude certain subcategories in a category archive page, try put the following code in your functions.php: function exclude_category( $query ) { if ( $query->is_category( 'myslug' ) && $query->is_main_query() ) { $query->set( 'cat', '-1,-1347' ); //Add your excluded subcategories ids } } add_action( 'pre_get_posts', 'exclude_category' ); If it's not the case, we need your code to see the whole picture.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
using nav menu id's I am trying to make a WP_Query that gets all pages / posts from the navigation id. I have the id's. I have a variable that holds the numbers and when I echo it out, this is exactly what I get 7,43,20,22,16,1051,18,26,9,24,28,10523 Reading in the codex, I should be able to use page_id. When I refresh the page, I do not get any posts or pages. Having tried many different versions of this query, this is where I am at right now. $page_query = new WP_Query( array('post_type' => array( 'post', 'page'), 'page_id' => array($number)));
If you have posts and pages then `page_id` isn't the correct parameter. You should probably use `post__in`. See `WP_Query Parameters`. Additionally, `post__in` accepts an array, whereas you have a string, so you'll need to use PHP to `explode` the string into an array. This is untested, but I think it should do it: $ids = '7,43,20,22,16,1051,18,26,9,24,28,10523'; $ids = explode(",", $ids); $page_query = new WP_Query( 'post__in' => $ids, 'nopaging' => true ); `nopaging` should do it, or `"posts_per_page" => -1` if it doesn't.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query" }
How to enqueue javascript for WP Customize options sidebar? I'm trying to add Chosen.jquery to the WP Customize options panel, so I can have an autocomplete box there. Is there any way I can do that? I tried with **admin_init** , **admin_footer** and **admin_print_footer_scripts** actions, but none seems to work inside of the Customizer. Any thoughts?
Use the action `customize_controls_enqueue_scripts`: add_action( 'customize_controls_enqueue_scripts', 'enqueue_customizer_scripts' ); function enqueue_customizer_scripts() { wp_enqueue_script(); // fill in the details here } To add inline scripts in the header, use the action `customize_controls_print_scripts`. See `wp-admin/customize.php` for details.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "theme development, themes, wp enqueue script, theme options, theme customizer" }
Showing a post depending on the Custom Field value <?php if (get_post_meta($post->ID, 'coach_location', true) == "Austria"): ?> ...this works, but manually checking each country and repeating the post content code is getting arduous, is it possible to do the country check automatically show the post content? So instead of checking each country like so: if austria: echo title & the_content if australia: echo title & the_content if south_africa: echo title & the_content ... all 196 countries of the world is it possible to automate this so I echo the title and content just once?
If you'd like to group posts by meta value, try the following code: $query = new WP_Query( array ( 'orderby' => 'meta_value', 'meta_key' => 'coach_location', 'order' => 'ASC' ) ); Please refer to the Codex. Let's say you'd like to print the Coach Location for each group, the sample code should be: $last_location = ''; while ( $query->have_posts() ) : $query->the_post(); $location = get_post_meta( $post->ID, 'coach_location', true ); if ( $last_location != $location ){ echo $location; $last_location = $location; } // echo the reset content endwhile; wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "advanced custom fields" }
'post' only for editor and administrator How can I make it so that only Administrator and Editor could access 'post' post-type? (just like 'page' post-type) I'm planning to only let Author and Contributor use the Custom-Post-Type which I've prepared beforehand...
The registered capabilities (and the other features) for registered post types are not saved in the database, but in a global variable, `$wp_post_types`. Being a global variable, editing it is easy. However you'll also need to manually remove the menu item, otherwise authors and contributors will be able to see it even if they cannot create/edit posts. In following function I'll set the capabilities for `post` post type coping ones from `page` post type. add_action('init', 'restrict_posts', 1); // registration run on init with priority 0 add_action('admin_menu', 'remove_post_from_menu', 1); function restrict_posts() { global $wp_post_types; $wp_post_types['post']->cap = clone $wp_post_types['page']->cap; } function remove_post_from_menu() { if ( current_user_can('edit_others_pages') ) return; remove_menu_page('edit.php'); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "user access" }
remove plugin admin menu in wordpress without installing plugin in v3.8.1 I follow instruction on this page to remove some admin menus: `remove_menu_page()` But is seems it only works on default admin menus. Admin menu added by plugins is not getting removed. For example, I tried removing admin menu of wordpress seo by yoast using remove_menu_page( 'admin.php?page=wpseo_dashboard' ); But the menu remains there. All other standard WordPress admin menus were removed except Yoast SEO. Any idea how can I also remove admin menu of plugins? I saw some similar questions but the recommended codes doesn't seem to be 3.8.1 compatible so I added this question to start a new fresh question specific to 3.8.1
add_action('admin_menu', 'remove_wpseo_admin_menu_links'); function remove_wpseo_admin_menu_links(){ remove_action( 'admin_bar_menu', 'wpseo_admin_bar_menu', 95 ); remove_menu_page( 'wpseo_dashboard' ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp admin, admin menu" }
WP_Query get posts where post_name is empty I want to get all the posts for which the post_name(slug) is not set/empty as well as a meta_key does not exist. $args = array ( 'post_type' => 'books', 'name' => '', 'post_status' => array('publish, draft'), 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => 'book_isbn_id', 'value' => 'dummy', 'compare' => 'NOT EXISTS', 'type' => 'NUMERIC', ), ), ); $query = new WP_Query( $args ); echo $query->request; It seems that `'name' = ''` or `'name' = ' '` is completely ignored from what I see from `echo $query->request`. Am I doing anything wrong?
You can try this: $args = array ( 'post_type' => 'books', 'name' => '', 'post_status' => array('publish, draft'), 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => 'book_isbn_id', 'value' => 'dummy', 'compare' => 'NOT EXISTS', 'type' => 'NUMERIC', ), ), ); add_filter( 'posts_where', 'custom_posts_where' ); $query = new WP_Query( $args ); echo $query->request; where function custom_posts_where( $where ) { remove_filter( current_filter(), __FUNCTION__ ); if( FALSE === strpos( $where, 'post_name' ) ) { $where .= sprintf( " AND %s.post_name = '' ", $GLOBALS['wpdb']->posts ); } return $where; } to search for empty post names.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, wp query, custom field" }
Is it possible to add post specific info in head of worpress post for OG use Im trying to implement this OG features on my site. < Is it possible to get post title, thumbnail url, and place it in the head section of a wordpress single post page? Thanks
Yes, the global post object is already set when `wp_head` is called. An example for a function body from this post: // restricted to singular pages only if ( ! is_singular() ) return; // there has to be a featured image set $thumb_id = get_post_thumbnail_id(); if ( empty ( $thumb_id ) ) return; // FALSE or array $image = wp_get_attachment_image_src( $thumb_id ); // nothing found for unknown reasons if ( empty ( $image ) ) return; // make sure it is a real url $src = esc_url( $image[ 0 ] ); // esc_url() returns an empty string for some invalid URLs if ( '' !== $src ) print "<meta property=' content='$src' />";
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp head, open graph" }
wp_insert_post featured image from library I know there are a lot of posts about it, but I don't want to upload a URL image to the library, I already have the image in the library and its IP. How can I use it with `wp_insert_post`?
You can use the function `set_post_thubmnail()`. After you inserted your post, just call this one, and you are ready to go. $yourpostid = wp_insert_post( $args ); // Define the post in the args first set_post_thumbnail( $yourpostid, $thumbnail_id ); // set the ID of your thumbnail to be the featured image of your newly created post.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "attachments, wp insert post" }
How do I Query 2 Custom Post Types? This is what I have, it **works** great except it only pulls from one CPT. I need it to pull from **two**. <?php $my_query = new WP_Query( array( 'post_type' => 'Portfolio' , 'Artwork' ) ); while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID; $the_post_ids = get_the_ID(); ?> If I use something like this as suggested elsewhere: <?php query_posts( array( 'post_type' => array( 'artwork', 'portfolio' )); while ( have_posts() ) : the_post(); $do_not_duplicate = $post->ID; $the_post_ids = get_the_ID(); ?> It doesn't work at all with parse errors that I cannot seem to fix. Unexpected ";". I am fairly new, could someone suggest something to try?
_Firstly_ , do not use `query_post()`, there almost never is reason to do so - take a look at When to use WP_query(), query_posts() and pre_get_posts. _Secondly_ , read the documentation about the things you want to achieve, here WP_Query - Type Parameters. _Thirdly_ , take a close look at what you're writing/copying there might be a syntax error in it, that's what you're telling us is implying. All that said, the following should do the trick. **Code:** $my_query = new WP_Query( array( 'post_type' => array( 'artwork', 'portfolio' ) ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Removing WordPress version number from included files I am trying to remove the WordPress version number from the file extensions for security purposes. Some of the enqueued files include the WordPress version number on the end of them, which can be seen from the inspector. For example: `<link rel="stylesheet" id="admin-bar-css" href=" type="text/css" media="all">` As you can see, ver=3.8.1 was apended. I've come across a few filters that remove the WordPress version number from the header and footer etc, but not from the included files. That filter looks like: function remove_version() { return ''; } add_filter('the_generator', 'remove_version'); But that does not remove the version number from linked files. Does any one know of a way to remove this version number?? Thanks
After further Googling I was able to come across a site that explains how to achieve this. < The second function on the page is quite helpful. This looks for "ver=" and checks that it matches the WordPress version number and then removes it. The first function on the page removes all version numbers from all files. The function that achieved the results looks like: // remove wp version param from any enqueued scripts function vc_remove_wp_ver_css_js( $src ) { if ( strpos( $src, 'ver=' . get_bloginfo( 'version' ) ) ) $src = remove_query_arg( 'ver', $src ); return $src; } add_filter( 'style_loader_src', 'vc_remove_wp_ver_css_js', 9999 ); add_filter( 'script_loader_src', 'vc_remove_wp_ver_css_js', 9999 );
stackexchange-wordpress
{ "answer_score": 15, "question_score": 2, "tags": "wordpress version" }
Creating two loops based on different logic I'm trying to figure out the best way to go about this and I have part of my solution, but I can't figure out all of it. My ultimate goal is within a certain page template, to show the newest post from a CPT of a particular taxonomy, this seems to be the easiest and accomplished with this: $args=array( 'post_type' => 'portfolio', 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC', 'posts_per_page' => 1, 'type' => 'featured' ); $portfolio_query = new WP_Query($args); The next part would be show all of other posts, with the exception of the post that is queried above. Can this be done with a single loop, or will I need multiple loops with offset logic? I'm lost on how to accomplish this. TIA.
This will most likely require two loops to the best of my knowledge. The second loop just needs to know to exclude the post you just queried. Something like the following should do the trick. $first_id = 5; // This should be set in the previous loop to the post ID of the post returned by your first query. $args2 = array( 'post_type' => 'portfolio', 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC', 'posts_per_page' => 10, 'type' => 'featured', 'post__not_in' => array( $first_id ), ); $portfolio_query_2 = new WP_Query( $args2 ); This info is taken straight from the WP_Query page in the WP Codex.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, custom taxonomy, wp query, offsets" }
Accidentally messed up URLs So I installed WordPress on my Apache server and I changed the URL in the WordPress Admin Control Panel to ` from ` and now it's taking me to my old `index.html` I made before I installed WordPress, even though I moved all my old stuff to a backup folder. Now I cannot get back into my WordPress admin CP. So my question is: How do I switch the URLs inside the WordPress files instead of the Admin CP (Cause I cannot get to it). How do I make the WordPress url to ` instead of ` P.S. I didn't include http:// on the links because I can't post more than two links with my rep.
Codex has an article on Changing The Site URL, you can edit values in database or override them in config. To have your site work from root you can either relocate WP there altogether or configure it to support root of the site, while still residing in subdirectory. See Giving WordPress Its Own Directory on the latter.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "apache, home url" }
put the content of a single post into og:description I'd like to have the content of the current single post loaded into the og:description meta property - but the `'. $content .'` doesn't output anything? This is what's in my header.php if (is_single()) { $content = get_the_content(); $desc='<meta property="og:description" content="'. $content .'" />'; echo $desc; } What could the problem be?
`get_the_content()` must be inside the loop, in header.php you can do this (don't forget to scape the content to use it as attribute): if (is_single()) { while (have_posts()) { the_post(); $content = get_the_content(); $desc='<meta property="og:description" content="'. esc_attr($content) .'">'; echo $desc; } } or even better, in your functions.php hook the wp_head action; also, I recomend using the excerpt instead of the content as descriptoin. (note the use of global $post and setup_postdata). add_action( 'wp_head', 'my_wp_head' ); function my_wp_head() { if (is_single()) { $post_id = get_queried_object_id(): $excerpt = get_the_excerpt( $post_id ); $desc = '<meta property="og:description" content="Blabla'. esc_attr( $excerpt ) .'">'; echo $desc; } //More stuff to put in <head> }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "the content" }
Post attachments doesn't show after manual db import I have wp db exported from domain www.domain1.com. I did manual database import using phpmyadmin to domain www.domain2.com. In database for particular post on new domain I have attachment image link that points to www.domain1.com/wp-content/uploads/2014/01/1.jpg. In front end somehow that link is changed to www.domain2.com/wp-content/uploads/2014/01/1.jpg returning 404 for that image even if db has good link. What can I do to fix that issue? Just to be clear I need that link to point to old domain because I want to keep those images in one place
As i understand you have used a function like `get_template_directory_uri()` or a similar one for your image URLs. This way I believe you are only saving relative URL. So domain change is reflected on the URL change. If you want the images to point to the old domain then you should hard code in the template of your new domain although hard-coding is not suggested.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "attachments, import" }
Creating a Digital Download facility and track downloads I need to make available Documents for download and I need to track the document name/number of downloads for each user and list of downloaders for each download, is this possible with WordPress, if so any suggestions ?
yes you can simply do all these with this plugin: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "user meta" }
Display trimmed version of the_post() I am using the following code to display pages on one page and would like to trim the content of each page on this display to 50 words and include images that are attached to the page. How do I go about doing this? $args = array( 'post_type' => 'page', 'post_parent' => '6', 'order'=> 'DESC' ); query_posts($args); while ( have_posts() ) : the_post();
First of all, never use query_posts, use WP_Query instead. To show 50 carachters of each one of the pages: <?php $args = array( 'post_type' => 'page', 'post_parent' => '6', 'order'=> 'DESC' ); $pages_returned = new WP_Query($args); while ( $pages_returned->have_posts()): $pages_returned->the_post(); ?> <div class="page-excerpt"> <h1><?php the_title(); ?></h1> <?php the_excerpt(); ?> </div> <?php endwhile; ?> Now for your 50 chars limit, on your functions.php add function custom_excerpt_length( $length ) { return 50; } add_filter( 'excerpt_length', 'custom_excerpt_length', 999 ); That should be it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "query posts" }
How do I mock HTTP requests for PHPUnit? I'm writing a plugin that makes requests to the Facebook graph API. As I don't want my unit tests to actually make these requests, how would I overcome this? My method calls both `wp_remote_get` and `wp_remote_post`. Searching there does seem to be a way to mock functions using `runkit`, here I want to avoid having contributers requiring too many dependencies so would like to avoid the above method. Is there any other options? My class extends the `WP_UnitTestCase` so I'm hoping maybe there's something from the wp unit-tests that I could use?
If you take a look at `WP_HTTP->request()` (which all related functions wrap) it provides a filter hook for the purpose of overriding making a request in favor of returning arbitrary data as response: // Allow plugins to short-circuit the request $pre = apply_filters( 'pre_http_request', false, $r, $url ); if ( false !== $pre ) return $pre;
stackexchange-wordpress
{ "answer_score": 17, "question_score": 10, "tags": "http api, unit tests" }
Themes VS Plugins If I am customizing a WordPress site, should I do that via a theme or a plugin? By customization I mean: 1. Add new custom post type 2. Add new fields to the Users 3. Add new widgets 4. Add custom permalinks I am leaning to creating new plugins for the above, and leave the theme for styling, however I wanted to confirm if this is the right approach. Thanks.
Yes, the types of customizations you are enumerating are _persistent_ to the site, regardless of theme changes. They are indeed commonly recommended to be contained in a plugin. Personally I consider there is exception from the rule when theme is uniquely developed to the site and de-facto _is_ site project. However I am tad in minority about it and most people insist on plugin approach even in that case.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins, custom post types, customization, themes, widgets" }
Multiple WordPress on Virtual Host I have AWS EC2 Linux server. Currently only one wordpress multisite mode is hosted in root folder (/var/www/html). Now I would like to host another wordpress site. So that I have enable apache virtual host. Here is my vhost.conf NameVirtualHost * <VirtualHost *> ServerName firstdomain.com ServerAlias www.firstdomain.com DocumentRoot /var/www/html </VirtualHost> <VirtualHost *> ServerName seconddomain.com ServerAlias www.seconddomain.com DocumentRoot /var/www/html/seconddomain.com </VirtualHost> I have one php test file inside seconddomain.com folder and I can browse by www.seconddomain.com After that I download wordpress and copy into seconddomain.com folder and change the wp-config.php. But I got the error "This webpage has a redirect loop". Is it because I have one wordpress in root folder or other security reason? Regards, Alex
Thanks for comments. I can manage to host two separate WordPress site on VirtualHost EC2 Linux AMI. My mistake is I have created the vhost.conf file in under /etc/httpd/conf.d. Correct way to enable VirtualHost on EC2 Linux AMI is as follow : 1. go to /etc/httpd/conf 2. open httpd.conf file 3. go to end of file 4. uncomment NameVirtualHost *:80 line 5. add the virtual host Thanks, Alex
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, virtual hosts" }
Hide mu-plugins list I'm using mu-plugins, < These plugins are showing in plugins.php, < Is there any way to hide it? Thanks.
The solution to this request is filtering `show_advanced_plugins`. This filter is called twice, once for `mustuse`\- and once for `dropins`-plugins. The filter accepts two parameters, the first one being the standard value (`true`), and the second one being the type of the advanced plugin (Must-Use and Drop-In). So returning false does the trick, if your condition is met. If you want Dropt-Ins to be hidden as well, just set the function to `return false`. Please be aware that a Plugin can alter this filter, so you may have to change the priority to achieve the desired results (3rd parameter). Also return the `$default` value in the standard case, to allow other functions the same functionality. And here comes the code: add_filter( 'show_advanced_plugins', 'f711_hide_advanced_plugins', 10, 2 ); function f711_hide_advanced_plugins( $default, $type ) { if ( $type == 'mustuse' ) return false; // Hide Must-Use return $default; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "mu plugins" }
Gist shortcode is not working I freshly installed a brand new Wordpress for testing purpose as I am intending to refresh my current website. One of the requirement I have is to be able to embed code from Gist. Following the Wordpress documentation, newer version comes with a specific shortcode for Gist : Gist Shortcode The issue is that it does not work at all. I tried pasting simply the url on a single line or wraping it around [gist] tags but nothing works. The url simply displays as raw text inside the post. I do know that some plugins provide the same functionality but I really wish to use the Wordpress builtin functionality. My site has been automatically hosted and installed on an Azure website, is running PHP 5.4 and Wordpress 3.8.1. Thanks for your help.
Gist tags and oembed handling is specific to WordPress.com, and doesn't come bundled with standard WordPress from wordpress.org You will need to acquire a plugin to register gists as an oembed provider, or add embed tags. There are plenty of plugins that do this available, I use this one. If you'd like to write your own, you'll want to use the `wp_embed_register_handler` function as a starting point.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 1, "tags": "shortcode, code, embed" }
Give wp link pages it's own template Here's the scenario, I'm working on a site with 100s of of paged posts using the wp_link_pages tag. The issue I'm having is that they're things I want displayed on the main post that I don't want display of the paged parts of the post and vice versa. How can I achieve that? And is it possible to give the paged parts of a post their own template?
In your single.php add this example code inside the loop: <?php global $page; if ($page == 1) {?> <div style="color:red;">This text should only appear on first page of the post!!!</div> <?php } ?> you can change the div with your thing that you wanted to display only on the first post page..
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates, paginate links, nextpage" }
Order Custom post type loop by custom field (datepicker) I know there are a lot of articles and documentation on this but I can't seem to figure it out. I have a custom post type 'agenda' wich is made for events. I want to sort this by the eventdate. For this, I made a custom field (datepicker) using the ACF plugin. I've found some documentation on the ACF website wich learned me how to echo the date in dutch format and also an article about sorting the posts by custom meta value. But I can't get it to work. The key for my custom field is: datum_agenda Codes I have already tried ( in the $args of the loop): 'orderby' => 'datum_agenda' & 'meta_key' => 'datum_agenda', 'orderby' => 'meta_value_num', 'order' => 'DESC' What am I doing wrong here? Seems like my code can't seem to find my meta_key or something because it still sorts by the autovalue.. (the normal post date)
Your second approach should in my mind actually work, you do it like this: **Code:** $args = array( 'post_type' => 'agenda', 'posts_per_page' => -1, 'meta_key' => 'datum_agenda', 'orderby' => 'meta_value_num', 'order' => 'ASC' ); $my_query = new WP_Query( $args ); There are two pages at the ACF documentation you might want to read: Date Picker and Order posts by custom fields. Besides that the only thing that comes to mind would be _how is the date formated_ and might the problem originate there, having `yymmdd` as value for the ACF »Date Picker« field »Save format« is recommended.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom field, advanced custom fields, order" }
Custom Meta Boxes and Fields Multicheck Issue I'm using Custom Meta Boxes and Fields by Justin Sternberg and its pretty great, however there's been a huge issue with using the multicheck checkbox options for me. This is what the plugin's code returns: '_cmb_seostats_multicheckbox' => array (size=22) 0 => string 'alexa_tr' (length=8) 1 => string 'alexa_bl' (length=8) 2 => string 'google_pr' (length=9) 3 => string 'google_bl' (length=9) 4 => string 'indexed_x' (length=9) How do I test those checkbox options within an if statement?
Use the in_array() function, like so: if ( in_array( 'check2', $test_multicheckbox ) ) { echo 'Check Two is checked'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, metabox" }
Changing order in which custom fields appear in dashboard I have several custom fields for my CPT. In dashboard page of my CPT, when editing a CPT, I see my custom fields in "custom fields" box. But I want to change the order in which they are displayed. Is it possible?
If you're talking about _the_ WordPress custom fields (no external resource like plugin etc.), then the answer is: No, unfortunately not. The meta box calls `has_meta` and `list_meta` \- and none of these functions provides suitable filter/action hooks. The custom fields are ordered by `meta_key,meta_id`. * * * Of course, you can set up your own meta box. All you need to change is the call of `has_meta` \- and adapt the SQL `ORDER BY` clause.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field" }
loginout function customization I want to make `login / logout` function inside my header to display when the user is logged in **Logged in as,{user name}** where **{user name}** should be wrapped inside an anchor tag with a custom permalink inside the `href` attribute. I've found this function `<?php wp_loginout( $redirect, $echo ); ?>` but I do not know if it's possible to modify this function to do what I need. Does anyone have any suggestions on how can I do this ? Thank you !
You might be looking for a logged in conditional. From the WP Codex, you might be able to try in your theme (untested): <?php if ( is_user_logged_in() ) { get_currentuserinfo(); echo 'Logged in as ' . $current_user->user_firstname; } ?> * * * **EDIT** After consulting the WP Codex on the topic, I was able to display my user's identity using the following: if ( is_user_logged_in() ) { global $user_identity; get_currentuserinfo(); echo 'Logged in as ' . $user_identity; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, customization, users, login" }
Why write markup for index.php? As I understand, index.php (a required template) is used when a more specific template is unavailable---according to the template hierarchy. My question is, if I create all the specific templates that my theme uses (e.g., home.php, single.php, page.php, search.php, archive.php, 404.php, etc...), then why bother writing any markup in index.php at all? I might as well just leave it blank? Is there a reason to fill out index.php?
WordPress might extend the existing template hierarchy in a future version. Your users would get a blank page after an upgrade. So write at least the basic loop, header, footer and pagination. Another point: I use and see at the `index.php` usually as _the default template_. I treat its layout as the core concept and all other templates as specialized variations. Your theme will be easier to understand if you build a complete `index.php` that doesn’t look like a forgotten stepchild.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "templates, html" }
URLs to images get messed up after migration I migrated a website from one host to another, and I am having a weird issue I never encountered before. The urls to images in html are fine, but the full path to the image has a broken url, the domain outputs twice. So here is the code generated for an image: `<img src="subdomain.domain.com/wp-content/uploads/2013/12/aleksandra.jpg" class="attachment-full wp-post-image" alt="aleksandra">` And here is the full path to the image in inspector: ` If you need more info please do not hesitate to ask. Any help is much appreciated. Thanks
I figured out the problem, when I was exporting the database using Migrate DB plugin, I didn't put the ` before the new domain... so all the internal links were broken.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "migration" }
Is it possible to set up multistore in Woocommerce? Is it possible to have a multistore in WooCommerce? I want to divide my WooCommerce store into 3 distinct stores with the toys showing up in 3 different collection names called: * remote cars * robots * funny Is it possible to set up up 3 different stores or collections using WooCommerce? Or do I need to go for Magento?
Woocommerce is a plugin for wordpress and cannot run multiple stores. However you may want to run wordpress as a multisite installation and for each site, you install plugin and can control all three stores from one wordpress admin. However i will recommend Magento, as its capable of multi store. Hope it helps
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, plugin development, multisite, e commerce, woocommerce offtopic" }
How to temporarily redirect front page of a network to one of the sites/blogs? After setting up a multisite wordpress, I'd like to be able to redirect the root (front page) to one of the blogs. To understand the context, I'm talking about an NGO that organises events, while active the homepage should redirect there. The solution I found on a couple of forums involved manually changing the ID of the intended target site. Is there a more elegant way to do this?
This code goes in your child themes functions.php file. add_action( 'template_redirect', 'wpsites_redirect_ms_front_page' ); function wpsites_redirect_ms_front_page() { if ( is_main_site() && is_front_page() ) { wp_redirect( ' 302 ); exit; } } Something like this should work (untested). **Modify Code** Simply swap out the URL in the code above. You can also change the 302 to 301 or any other type of redirect.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "multisite, redirect" }
How to redirect users to custom lostpassword page? How to redirect users to custom lostpassword page when they click on the Error: Lost your password?. Because I set a redirect for `wp-login.php` to my custom login page. when a user click on Error: Lost your password? it requests for `wp-login.php` and then automatically redirects to custom login page. I know the function is present on `wp-login.php` file but I don't know what changes shall I make to make this possible. Please help. I have also renamed wp-login.php.
If you only want to adjust the link of the _lost password_ page, then there is a designated filter for that: function wpse_133647_custom_lost_password_page() { return home_url('/lost-password'); } // function wpse_133647_custom_lost_password_page add_filter('lostpassword_url', 'wpse_133647_custom_lost_password_page');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, functions, redirect, wp login form" }
How to add active class on current menu item page? I have two links: Products and News. When i click on Products or News, it returns me an archive page that contains some posts, when i click on a post it returns me a single page of this post. In the menu I use this code on `<li>` to add a class called active if the page is home: <li<?php if(is_home()) {?> class="active"<?php } ?>> But i dont know how to do it when I have two archive pages and two singles pages. If i use `if( is_archive() || is_single() )` it'll add class on both menu itens. Some help would be appreciated.
You could add conditional classes for each in your child theme functions file: Here's one example you can modify to suit your own needs. add_filter('nav_menu_css_class' , 'wpsites_nav_class' , 10 , 2); function wpsites_nav_class($classes, $item){ if( is_archive() && $item->title == "Products"){ $classes[] = "products-class"; } return $classes; Source < You can then style your nav menu using the new class in your child themes style.css file. .products-class { Your CSS declarations } This CSS code is conditional based on the PHP code above.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "menus" }
Display WooCommerce newest product reviews on top By default, woocommerce product reviews are listed in chronological order. How do you get the newest review to appear first?
I couldn't find this documented anywhere, but the solution is pretty simple. In `single_product_review.php`, the arguments passed to wp_list_comments are filtered: ` wp_list_comments( apply_filters( 'woocommerce_product_review_list_args', array( 'callback' => 'woocommerce_comments' ) ) ); ` by adding `reverse_top_level` to the arguments, the order is reversed. Add the following code to your theme's functions.php: // show newest product reviews on top add_filter( 'woocommerce_product_review_list_args', 'newest_reviews_first' ); function newest_reviews_first($args) { $args['reverse_top_level'] = true; return $args; }
stackexchange-wordpress
{ "answer_score": 9, "question_score": 3, "tags": "filters, woocommerce offtopic" }
How to show an error message after publishing a post? I'm using the `transition_post_status` hook to perform some operations after publishing a post. In some conditions I would like to show an error message in a red box under "Edit Post" and above "Post published": !Post pushlished How can I do that?
I wouldn't use that hook. Here's why Try something like this using admin_notices. function wpsites_admin_notice() { $screen = get_current_screen(); if( 'post' == $screen->post_type && 'edit' == $screen->base ){ ?> <div class="error"> <p><?php _e( 'Updated Demo Message!', 'wpsites' ); ?></p> </div> <?php }} add_action( 'admin_notices', 'wpsites_admin_notice' ); Untested.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "wp admin, hooks, publish, post editor, errors" }
Advanced Custom Fields if else issue Ok, I think I have a simple fix here. I'm using ACF to link health reports to specific dogs on a breeder website. But, not all dogs have the same reports, and I don't want to show a dead link if no ACF value is available. So, I wanted to use an if statement but can't quite get it to work. Here's my code: <?php $values = get_field('cardiac'); if($values) { echo '<a rel="lightbox" href="'.<?php the_field('cardiac'); ?>.'">Cardiac</a>'; } else { echo ''; } ?> Any help would be appreciated.
My guess is that your problem is that your field type is returning some non-empty value, even if it's not a URL. For instance, do you have " set as a default value for that field in the admin? If that were the case you could need to use the following as your test: `if( $values || $values !== ' )...` Alternately, your field may be returning an empty array or some other kind of "unechoable" value. Try putting `var_dump( $values )` after you set the `$values` variable and see what you're working with. Then adjust your `if()` statement to account for other possible non-empty values you may want to weed out before outputting a link. * * * **Update: Another issue** Also, you shouldn't use `the_field()` in an echo statement since the_field already echos its output. Change this: `echo '<a rel="lightbox" href="'.<?php the_field('cardiac'); ?>.'">Cardiac</a>';` To this: `echo '<a rel="lightbox" href="'. $values .'">Cardiac</a>';`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "advanced custom fields" }
How to include posts with a theme I am making a theme and would like to submit the posts that i have made with the theme to the user. How can this be done?
Export the posts via the exporter at `wp_admin->Tools->Export` and bundle the resulting file. Provide the end user with instructions for importing them-- basically, install the WordPress importer and then visit `wp_admin->Tools->Import`. Please do not try to force installation of your posts automatically as it will insert data into the user's database. That just isn't friendly.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, import" }
how to redirect to url.com/wp-admin if url.com/admin is typed in? How would I create a wordpress function that will redirect a user to myurl.com/wp-admin if they type in myurl.com/admin? I would like to have this as a wordpress function.
Hook into `template_redirect`, inspect the request URI, and redirect to the return value of `admin_url()`. add_action( 'template_redirect', function() { $request = untrailingslashit( strtolower( $_SERVER['REQUEST_URI'] ) ); if ( 'admin' === $request ) { wp_redirect( admin_url() ); exit; } }); Note: always use `admin_url()` and the other built-in URL functions, because they will take care of the proper scheme (`https` or `http`).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "admin, wp admin, redirect" }
How can i retrieve all custom registered taxonomy? i am trying to find a way to retrieve all registered taxonomies i was looking at get_taxonomies() but i cant seem to get only the custom registered ones. any idea ?
The built-in taxonomies are registered with the parameter `_builtin` set to `TRUE`. To get all custom taxonomies, ask for `'_builtin' => FALSE`: add_action( 'wp_footer', function() { $taxonomies = get_taxonomies( array( '_builtin' => FALSE ) ); print '<pre>' . print_r( $taxonomies, 1 ) . '</pre>'; });
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom taxonomy" }
wordpress post not showing my "<somehting>" text>? I am trying to make a post where there is a text line : > some libraries to run which we will import by using "`#include <filename.h>`" command. instead of outputting the text as it is. It shows as: > some libraries to run which we will import by using “#include ” command. in post so `<filename.h>` is missing for some reason. I am quite sure I am missing something here but unable to find. I think for some reason WordPress escapes anything between <> tags so how can i show them if i need to?
You have to escape th `<` and the `>` with `&lt;` and `&gt;`, otherwise WordPress will remove the “unknown tags”. You could also filter `pre_kses` to change the output before it gets stripped. add_filter( 'pre_kses', function( $str ) { // find and escape < and > on specific positions, then return $str; });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, text, escaping" }
Custom Same Page Search I've added a custom form to one of my page templates. It submits to itself `$_SERVER['REQUEST_URI']` in hopes I can grab the `$_GET` values and modify my query using `pre_get_posts`, but instead it goes to 404. So to clarify, I don't want to use search.php, I want it to post back to my page template and modify my query to show the "filterd" results instead of 404ing. I've tried using `pre_get_posts` to test if it's 404 or search, but I also don't want to stop anything else from 404ing. So how can I use a query on the same page / url / page template without needing to reply on `search.php` or having my query cause a 404? So with the custom search form in place the url is currently ` \- and I want to modify the query on the specific page depending on the `$_GET` value.
Don't use a query variable that is used by the WordPress Core. That is, none of these. You are using `year`. WordPress will latch onto that and process the request according its internal systems. Try something more distinct like `hmg_year`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, query, search, page template" }
Post Filter by Date and time I'm trying to get wordpress post by filtering date and time, for example get post 01/02/2014 to 07/02/2014. thanks for the help me.
Try to use `new WP_Query` for this. Add a new query and pass below argument. $args = array( 'date_query' => array( array( 'after' => '2014-02-01', 'before' => '2014-02-07', 'inclusive' => true, ), ), ); $my_query = new WP_Query( $args );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts" }
How can I specify that an area of my theme contains widgets? I am pretty new in WordPress theme development and I am developing a theme that use BootStra CSS framework I have to do that a specific area of my theme can contains some widget\module (I don't know what is the correct name in WP, I am referring to the settings in the backend that show some components output as a gallery image or a slideshow. Someone can help me to understand this argument? from what can I start to do this operation?
You can add widgets conditionally by adding a conditional tag in your template file. You also mentioned a image slider. You can conditionally load the slider so it only displays where you want like the front page only. An example would be to add this code in your header.php file so the slider only loads on the front page. <?php if (function_exists('slider_template_tag') && is_front_page()) { slider_template_tag('82'); }?> You can do the same with the widgets. <?php if ( is_active_sidebar( 'left-sidebar' ) && is_page('007') ) : ?> <ul id="sidebar"> <?php dynamic_sidebar( 'left-sidebar' ); ?> </ul> <?php endif; ?> This displays the widget area only on the page with i.d of 007.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, widgets" }
Uncaught ReferenceError: jQuery is not defined . How do I define it correctly? The following code is in the same php script. But I get `Uncaught ReferenceError: jQuery is not defined` in chrome debugger. validate.js is in plugins/validate/validate.js I know this is the problem , as I tried validate.js when not using wordpress, by including it externally, & it worked fine. I am using the code below, on a page. What is the solutions please? add_action( 'init', 'load_jquery' ); function load_jquery() { wp_enqueue_style( 'jquery'); } function add_my_css_and_my_js_files() { wp_register_script( 'validate', plugins_url( '/validate.js', __FILE__ ) ); } add_action( 'wp_enqueue_scripts', "add_my_css_and_my_js_files" );
Just use `deps` parameter to include jQuery, change your code to: function add_my_css_and_my_js_files() { wp_register_script( 'validate', plugins_url( '/validate.js', __FILE__ ), array( 'jquery' ) ); wp_enqueue_script('validate'); } add_action( 'wp_enqueue_scripts', "add_my_css_and_my_js_files" );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "jquery" }
API for creating blogs on Multisite? Is there some API or plugin that allows for creation of sites on a multisite install? Jetpack doesn't seem to allow it, and the xml rpc doesn't seem to support multisite. Is there something I can use as a JSON API or some other sort of http call to do this?
I ended up creating one myself. I'm not sure if the new wordpress rest API contains functionality that duplicates this so you may want to investigate that first. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite, api" }
How to import CSV into Custom Post Type custom fields? I have created a Custom Post Type and then used a plugin to create the custom fields for that post type. It will display a type of membership: Name Address Zip Website But I am stuck on how to take the csv file I have, which has 700 entries and import it to create 700 entries under the CPT I created and autopopulate the custom fields I created. I tried a lot of plugins, but none seemed to do both parts. Some let me just select the CTP but I couldn´t get all the fields populated. Just needed to know best way to accomplish this.
I'm using a plugin called **TurboCSV** (found here, at the time of writing). The plugin offers support to add data to your various custom fields, which need to be created before the import takes place. In my personal use, I was able to successfully import thousands of items from one **.csv** , including hundreds of taxonomy terms and custom fields. Have a look at the plugin's documentation to see how involved it is and how much you're able to do.
stackexchange-wordpress
{ "answer_score": -2, "question_score": 9, "tags": "advanced custom fields, import, csv" }
Get_the_author doesn't return author name I insert author box below my post and use get_the_author to return author name but it doesn't working. It also doesn't working with Search post by author. Hope everyone give me solution, thank in advance. !enter image description here
Echo it out... `<?php echo get_the_author(); ?>`
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "php, posts, author, single" }
How can I add a Categories page link to a menu? Not a link to a specific category, but a link to a page that lists all categories of a custom post type (WooCommerce Products).
WooCommerce shows a listing of product categories at `/products`, which can be added to a menu as a simple link to that url. It took me a while to find that url. To override the categories page template, grab a copy of `templates/content-product_cat.php` from the WooCommerce repo and place it at `woocommerce/content-product_cat.php` in the child theme.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, menus, dashboard, woocommerce offtopic" }
How to get the blogs owned by a user? I have setup WP MU and I would like to get a list of blogs a user owns. Is there a method that gets this info? **More info:** I only have one page for the user to login. I need to get the blogs they own to redirect to their own blog.
Yes, there is a method called get_blogs_of_user($user_id); Supply the user id and echo it. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, users" }
Add a user to a specific blog when they register? I've setup a WP MU site and I need to know how to sign up a user to a specific blog when they register. As it is now, if a visitor is visiting a specific site and they click the register button they are taken to the main network site and then they are given the option to register as a user or create their own blog. I can create my own registration page but I'm not sure how to add that user to a specific site. This is what I have so far: $meta = apply_filters( 'add_signup_meta', array() ); $emailSent = wpmu_signup_user( $user_name, $user_email, $meta );
I think I found it, <?php add_user_to_blog( $blog_id, $user_id, $role ) ?> <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite, users, user registration" }
Wordpress MAMP Installation Issue I have MAMP configured in my machine and I've been using it to run multiple Wordpress installs with no issue until this new site where the Wordpress install is in a subdirectory. The site is installed under htdocs and it has the following structure: /mylocalpath/htdocs/www.mysite.com/Web Applicatin/WordpressInstallCoreFiles For some reason this keeps returning a 404. I followed the steps for "Wordpress in Subdirectory" but still no luck. I do have the hosts file set up correctly for the local domain. Any tips or ideas on how to get my site running on the subdirectory? Anything I can do in Apache to configure this correctly?
Turns out this was an issue with my current Apache install. After uninstalling an reinstalling the latest version of Apache, everything worked as expected.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "apache, local installation" }
flush_rewrite_rules() cancels the effect of add_rewrite_rule() As one of my plugin's features, I'm trying to define a custom url structure, like ` I'm using `add_rewrite_rule()` along with `flush_rewrite_rules()` on plugin activation, which works as expected. Until `flush_rewrite_rules()` gets called again, during another request, either by hand or by enabling another plugin that does so. When this happens, my rewrite rule suddenly disappears (I'm using Rewrite Rules Inspector to check this). The minimum code needed to reproduce the issue is this: <?php /* Plugin Name: PluginA */ register_activation_hook(__FILE__,'PluginA_activation'); function PluginA_activation() { add_rewrite_tag('%foo%','([^&]+)'); add_rewrite_rule('foo/([^/]+)','index.php?foo=$matches[1]','top'); flush_rewrite_rules(); } Any idea what I'm doing wrong?
Rewrite rules are stored in an option. When `flush_rewrite_rules()` is called, this option is removed, WordPress collects all rules registered during the _current request_ and writes that option new into the database. You registration doesn’t run on every request, so it doesn’t exist, when the option is rewritten. Register the rule on ever page load, flush the rewrite rules on activation. Separate the registration and the flush. register_activation_hook(__FILE__,'PluginA_activation'); add_action( 'wp_loaded', 'PluginA_rewrite_rules' ); function PluginA_activation() { PluginA_rewrite_rules(); flush_rewrite_rules(); } function PluginA_rewrite_rules() { add_rewrite_tag('%foo%','([^&]+)'); add_rewrite_rule('foo/([^/]+)','index.php?foo=$matches[1]','top'); }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "rewrite rules" }
Block wordpress style for my plugin admin page I have my own style for my plugin, it works, but wordpress adds a style too, and the page is not looking very ok. Is there any way to block wordpress style for my plugin administration page?
The admin stylesheets combines rules for everything: tool bar, left menu, footer and some common elements like tables and forms. You cannot disable just a part of it. If you want to apply your own rules, use a higher specificity in your CSS rules. Normally, all plugin pages use the same wrapper element: <div class="wrap"> <!-- page content here --> </div> You can add an `id` attribute here … <div class="wrap" id="unique_plugin_prefix"> <!-- page content here --> </div> … and use that selector in your styleheet: #unique_plugin_prefix p { margin: 1em 0; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, css, codex" }
Remove all nav menu classes ( but keep useful ones... ) I'm trying to remove all menu-item classes (except for `.current-menu-{item/parent/ancestor`} and `.menu-item-has-children`) function custom_nav_menu_css_class($classes) { $classes = preg_replace('/^((menu|page)[-_\w+]+)+/', '', $classes); return $classes; } add_filter('nav_menu_css_class', 'custom_nav_menu_css_class'); This almost does the job, _except_ it removes `.menu-item-has-children`? Any idea what I should change, to exclude it from being removed? (P.S. I'd rather not use a custom walker...)
You could work with a white-list and replace the regular expression with something more readable: add_filter( 'nav_menu_css_class', function( $classes ) { $allowed = [ 'menu-item-has-children', 'current-menu-item' ]; return array_intersect( $classes, $allowed ); }); That would make it easier to maintain the white-list too.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, menus, customization" }
Set Current Category to Active in category.php Inside the category.php file I have a custom navbar which is... <ul class = "nav nav-tabs nav-justified"> <li><a href=" title="View all posts">All Categories</a></li> <?php wp_list_categories('orderby=name&title_li='); ?> </ul> I would like the li for the current category to have class = "active". How can I code this? Thank you
You can filter the output on `wp_list_categories`: add_filter( 'wp_list_categories', function( $html ) { return str_replace( ' current-cat', ' active', $html ); }); If you are stuck with an outdated PHP version … find a better web hosting. In the mean time, you can try this: add_filter( 'wp_list_categories', 'replace_current_cat_css_class' ); function replace_current_cat_css_class( $html ) { return str_replace( ' current-cat', ' active', $html ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories" }
Make query_post category name dynamic I have a working funtion: <?php query_posts('category_name=category');?> I want to make the category name dynamic to reflect the page title. Something like this: <?php query_posts('category_name='.the_title());?> But this doesnt work, & nothing I do seems to have the desired effect.
Use `get_the_title()` replacing `the_title()`. Difference is `get_the_title()` returns the value while `the_title()` echos it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "query posts" }
Advanced custom fields if else statement I'm using the plugin Advanced Custom Fields. The following example code is given on the acf website for if statements. <?php if(get_field('field_name')) { echo '<p>' . get_field('field_name') . '</p>'; } ?> I have tried adding an else statement like so: <?php if(get_field('main_title')) { echo '<h1>' . get_field('main_title') . '</h1>'; } else { echo '<h1>' . the_title() . '</h1>' ; } ?> The snippet works perfectly if I enter data into the `main_title` field in WP Admin, but if it's blank, the default page title is outside the `<h1>` tags. Thank you for your patience. I'm a bit of a PHP noob!
You are using version of template tag that echoes result immediately and so unsuitable to concatenate in string. You should be using `get_the_title()` for this purpose,
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "advanced custom fields" }
Why do I need to register my custom post type a second time when flushing rewrite rules? If I register my custom post type when the `init` action fires (which is before plugin activation) why do I need to register my custom post type a second time when flushing rewrite rules (on plugin activation)? See the following example. add_action( 'init', 'my_cpt_init' ); function my_cpt_init() { register_post_type( ... ); } function my_rewrite_flush() { my_cpt_init(); flush_rewrite_rules(); } register_activation_hook( __FILE__, 'my_rewrite_flush' );
When a plugin is activated, the only thing that runs on that activation request is the activation hook. whatever you've got hooked to init has not and will not run on that request, so you need to register it in your activation before you flush rewrites. it's only after the plugin is activated, on the next request, that the init action fires for that plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, rewrite rules, activation, init" }