INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
CSS not applying in admin I am using SASS and grunt to merge all my seperate .scss files into a single minified css file, which is loaded using `wp_enqueue_style`. Works fine across the site but not in the admin area. Is there a special function needed to enqueue scripts for use in the admin area?
You need to hook `admin_enqueue_scripts` to enqueue scripts and styles for the admin side.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css" }
Changes only show when logged in? Changes I've made to my site only show when i'm logged in. According to various other threads it seems to be a problem with cache, however, i've completely deactivated my W3 cache plugin, and the problem still isn't resolved. Any ideas?
This does indeed sound like a cache problem. Plugins on the server side will cache the site for faster serving, while your own browser does its own caching to not have to repeatedly download the same web content. In Wordpress, any caching plugin should have a "clear cache" button, and your browser cache should have a setting for deleting cache. If you develop with your browser's developer tools open, your browser shouldn't cache.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "login" }
`#1215 - Cannot add foreign key constraint create table wp_pageviews ( ID BIGINT(20), count integer, primary key(ID), FOREIGN KEY (ID) REFERENCES wp_posts(ID) ) Error : `#1215 - Cannot add foreign key constraint` What is the reason for this? Why I can't create this table?
In order to make the `wp_posts(ID)` a `REFERENCE` for the `FOREIGN KEY`, you should also set the `wp_pageviews.ID`'s attributes as `UNSIGNED` and keep the same data type for the `wp_pageviews.ID` as (`bigint`) . Let me know if this helps you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "mysql" }
Issue On Displaying Pages with Post Name Permalink I have a simple Theme like below !enter image description here Right now when I navigate to localhost and site root directory I am able to see content from `header.php` , `footer.php` and `page.php`. then, I simply generated some pages for Navigation bar and to get a better URL I updated the permalink from `default` to `Post Name` format !enter image description here Now while I have the the clean Ur as: `Permalink: !enter image description here When I click to view the page I am getting !enter image description here I Google this and find some hints about the `(.htaccess)` so I just copied same format as Cedex) !enter image description here but still getting same result. Can you please let me know why this is happening? Thanks
In order to work permalinks properly, you have to enable 'mod_rewrite' module in your apache server. Other wise it could not run .htaccess file and that is why it shows 'Not found'. It will be working if the permalink is disabled or set to default, right?
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, permalinks, pages, urls, page template" }
display specific widget to a page im trying to display a specific widget i need for the header current im using a code to display all widgets but my problem is that if I add additional widgets it will destroy my site. <?php dynamic_sidebar( 'sidebar2' ); ?> <?php else : ?> <!-- This content shows up if there are no widgets defined in the backend. --> <div class="alert-box">Please activate some Widgets.</div> <?php endif; ?> code im using.. im trying to display this widget < i tried to use this code to call the widget but nothing happens I must be putting the wrong name of the widget or the code. i don't about backend code. <?php the_widget( 'WP_Language_Switcher' ); ?>
you can create new widget area. function header_widget_areas() { register_sidebar( array( 'name' => __( 'header', 'header' ), 'id' => 'header', 'description' => __( 'Insert something for about us text.', 'header' ), 'before_widget' => '<div class="widget span3">', 'after_widget' => '</div>', 'before_title' => '<h4>', 'after_title' => '</h4>', ) ); } add_action('widgets_init', 'header_widget_areas'); Then place your widget in that area from appearance. Then in your template where you want to display widget past this code. <?php if (function_exists('header_widget_areas')): ?> <?php dynamic_sidebar('header'); ?> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, widgets" }
Get the title before comma I am using this code to return the title of the post on a gravity form field. add_filter('gform_field_value_page_name', 'page_name_filler'); function page_name_filler($value){ return get_the_title() ; } However, usually the title of the post is too long and it overfills the field. Hence I would only like to retain the first portion of the title before a comma "," if it exists on the title. Usually I will have multiple commas on my titles. If a comma doesn't exist then the full title should be displayed.
Use `strtok()`: return strtok( get_the_title(), ',' ); You could also use my function `utf8_truncate()`. This is a little bit more flexible and it can handle long strings without a comma.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, functions" }
Differences between wpdb->get_results() and wpdb->query() Who can explain me the differences between `wpdb->get_results()` and `wpdb->query()` in making generic queries to wordpress db?
The difference, if you want to call it that, is that the `query()` is the most generalized method to do queries with `$wpdb`, the `get_results()` method on the other hand is a specific method, which does make use of the `query()` method to retrieve the specific results of this method and then does some work on the output.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 8, "tags": "query, wpdb" }
Using functions repeatedly instead of variables I think I know the answer already but I would like some clarification on what exactly is happening in the back end. Usually I call a wordpress function such as `get_post_meta($id)` and assign it to a variable if I wish to reuse it later on. What kind of performance hit would happen if I used `get_post_meta($id)` over and over again instead of the variable, say in an if statement or in a while loop?
The difference is going to be pretty minimal, I'd expect. There is overhead to using the functions, which you could save by storing your output in a variable. (WordPress does a pretty good job at caching the queries though.) And the variable is going to be more convenient as it is probably fewer characters than the function. A drawback to using a variable is that code will not be able to hook into the functions if that code runs after you've saved the value to the variable, so that could potentially cause trouble. I am going to answer "you probably don't need to worry about performance but there are other things to think about".
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "performance" }
How to use ACF repeater? I'm using ACF but the `get_field` option doesn't work when using a repeater field <?php echo get_field('field_name'); ?>
You need to use a `have_rows()` loop, then use `get_sub_field`. ACF provides great documentation, which happens to be the first google result, here
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "advanced custom fields" }
Unknown column 'siteurl' in 'where clause' WPDB outside I am trying to get Mysql values from outside wp. My code: define( 'BLOCK_LOAD', true ); require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' ); require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' ); $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); $wpdb->get_var("SELECT option_value FROM wp_options WHERE option_name = siteurl"); What i missed ?
option_name is type VARCHAR, iow. a string Try: $wpdb->get_var("SELECT option_value FROM wp_options WHERE option_name = 'siteurl'");
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wpdb" }
exclude one child by id from $post->post_parent I'm trying to exclude one child from the children of a parent. What do I need to change here? thanks if ( $post->post_parent == '4426' || in_array( '4426', $post->ancestors) && (!is_page('4430') ) { // Who We Are //do something }
Maybe it's just a matter of parentheses. if ( ( $post->post_parent == '4426' || in_array( '4426', $post->ancestors) ) && !is_page(4430) ) { // Who We Are //do something } I'm assuming `is_page` accepts an Integer being the page ID and `4430` is not the slug or page title.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts" }
how get comments only on post of current logged in user? I need a query that get all comments from only the posts where the currently logged in user is the author. Each user (author) can post a new post. Then I need to show a list of their own posts ( that already works). Now I want a list of all comments (on the currently logged in users posts). So the author has a quick overview of all comments on their posts.
Using the @shanebp ideas of using `get_comments`: $args = array( 'post_author' => get_current_user_id(), // It will use the current logged in use to grab the comments ); $comments = get_comments( $args ); // Referer to $list_args = array( 'reverse_top_level' => false // Show the latest comments at the top of the list ); wp_list_comments( $list_args, $comments ); This will display the list of comments done on posts from one user.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "comments" }
Disable Admin CP authentication (or auto login) Is there a way to allow _anyone_ into the admin panel, without the need to log in? Or, if need be, is there a way to have Wordpress auto-login using a certain set of credentials? This seems like something that should be trivial, but it appears nobody else has found a use case for this as of yet.
Here is example code that will log everyone in as 'autologinuser'. The 'autologinuser' needs to be created and given a role prior to using this code. function my_autologin() { if (!is_user_logged_in()) { $uid = 'autologinuser'; $user = get_userdatabylogin( $uid ); wp_set_auth_cookie($user->ID); wp_set_current_user($user->ID); do_action('wp_login', $user_login); // optional } } add_action('init','my_autologin');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp admin, login, wp login form" }
How do I link a Post Type to a Template in Masterplan? I've made a new .php theme page and want to use that file on one of my Post Types. In the Templates part of Masterpress Ive added my Post Type in the availability section. However, when I view my posts with that Post Type their theme doesn't change. I cannot see where to select the theme on the Edit Post Type page. Does anyone know how I can select a theme for a particular Post?
I have never used Masterplan nor Masterpress, however as far as the template hierarchy is concerned, it seems to be no different from the standard Wordpress way of dealing with it - See Masterpress Docs I assume that if your (Custom) Post Type is correctly registered through Masterpress interface, it should be registered in Wordpress. So you probably just have to send your PHP template, renamed to `single-{post_type}.php` on your sever, in your current theme folder. For instance if your post type is registered under "trees" (take not-rewrited slug, or front-end name as it seems to be called in Masterpress), then your PHP file should be named `single-trees.php` It should then be used automatically by WP when accessing a post from this Post Type.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, themes" }
Best way to load WordPress Bootstrap My script needs to load the whole WP in order to work probably. I'm currently doing it this way if ( !defined('ABSPATH') ) { /** Load WordPress Bootstrap */ @ini_set('include_path', '../../../'); require_once('../../../wp-load.php'); } //additional html stuff do_action('my_custom_hook'); //more html stuff which works most of the time. Sometimes people get a Fatal error for a missing file though. The script is located at wp-content/plugins/my-plugin-slug/script.php What's the best way to load it?
Requiring a file using relative path is never a good idea, that because wp content folder can be easily changed and that make your code fail. You should convert your file into a MU plugin (you only need to save it `wp-content/mu-plugins` folder) and change it to something like: add_action( 'wp_ajax_super_custom_stuff', 'my_super_custom_stuff' ); add_action( 'wp_ajax_nopriv_super_custom_stuff', 'my_super_custom_stuff' ); function my_super_custom_stuff() { // additional html stuff do_action('my_custom_hook'); exit(); } After that, to make the script run, instead of calling the url you can call This will always work because `wp-admin` folder, unlike `wp-content`, can't be changed because it is hardcoded in a lot of places. You can run the script from a linux crontab using something like: wget -q --spider "
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp load.php" }
How to search display_name column when using WP_User_Query I'm using WP_User_Query to bring back a list of users. According to this article, I can focus the query on particular columns (I'm assuming in the wp_users table) using the search_columns param. My query: $args = array( 'search' => 'Rami', 'search_columns' => array( 'user_login', 'user_email', 'display_name' ), ); $user_query = new WP_User_Query( $args ); My aim is to have my query look in the display_name column but that doesn't seem to be working. Interestingly, display_name isn't a mentioned column in the article example but it is definitely a column in the wp_users table. How can I search the display_name column when using WP_User_Query?
You can try this: /** * Add support for the "display_name" search column in WP_User_Query * * @see */ add_filter( 'user_search_columns', function( $search_columns ) { $search_columns[] = 'display_name'; return $search_columns; } ); where we use the `user_search_columns` filter to modify the available search columns. So what fields can we use with this filter? Here's the list of all the fields in the `wp_users` table: x ID x user_login user_pass x user_nicename x user_email x user_url user_registered user_activation_key user_status display_name where I've marked the default search columns with an `x`.
stackexchange-wordpress
{ "answer_score": 12, "question_score": 4, "tags": "php, query, wp user query" }
How to get post thumbnail to be equal to set media size I'm new to learning WP theme development so I may not have worded the title perfectly but that's the best way I could think to explain it. My theme is on a localhost so I can't link to it but here is a screenshot: What I want is for the_post_thumbnail to always fill the specified thumbnail media settings. Currently the thumbnails will be different sizes depending on the width / height ratio. I have gone into WP Dashboard and set the media thumbnail size for medium at 250px wide by 150px tall. I want the image to always fill that space, don't care if it's cut off but I want it to be that size. Thanks, I hope I explained it correctly.
the_post_thumbnail allows for size specificiations. So you would do: <?php the_post_thumbnail('medium'); ?> if you changed the image dimensions in the admin, you will need to go back and re-upload the images so they crop to the correct size that you set up If the issue is the dimensions of the image you are probably looking for a hard-crop. The best bet is to set up a new image size with add_image_size in your functions.php. add_image_size( 'new-image-name', 250, 150, true ); then re-uploading images then <?php the_post_thumbnail('new-image-name'); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post thumbnails, media" }
How to check if a string is a valid URL WordPress provides a helpful function called `is_email()` which checks if a given email address is valid. Is there a similar function available to check if a URL is valid? I tried `is_url()` but that was just wishful thinking on my part. Ref: <
Use the native php function Filter Validator if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) { die('Not a valid URL'); }
stackexchange-wordpress
{ "answer_score": 12, "question_score": 13, "tags": "php, validation" }
Output html source tags inside shortcode I have made a custom popup tiny mce button to add source code.This put shortcode like this [source] <h1>Hi</h1> [/source] To capture output I used function caption_shortcode( $atts, $content = null ) { $content = do_shortcode($content); return '<span itemprop="articleSection">'.wpautop($content).'</span>'; } add_shortcode( 'source', 'caption_shortcode' ); This doesn't show `<h1>Hi</h1>` rather it convert h1 html tag.How can I make this show like `<h1>Hi</h1>`?
Try the following code: function caption_shortcode( $atts, $content = null ) { $content = do_shortcode($content); return '<span itemprop="articleSection">'. str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), $content ) .'</span>'; } add_shortcode( 'source', 'caption_shortcode' ); remove_filter( 'the_content', 'wpautop' ); remove_filter( 'the_excerpt', 'wpautop' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, tinymce" }
Adding social share buttons for individual images on a web page I am looking for a way to add social share buttons (Facebook, Twitter and Pintrest) for all individual images on a given web page. Here is an example: < As you can see in the above URL, each image has its own share buttons. Is there a simple way to achieve this for a Wordpress blog post? Thank you!
Have you tried this plugin from Addthis: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "images, sharing" }
Need 404 behaviour for blank parent page My pages look like this * Home (Has content) * Products (No content) * Product 1 (Has content) * Product 2 (Has content) * Product 3 (Has content) * Contact (Has content) I only created the "Products" page so the navigation makes sense in the Pages structure, however it has no content so I need it to show the 404.php when you try to access it via the direct URL:
In functions.php function productsPageRedirect_404() { global $post; if( is_page('products') ) { global $wp_query; $wp_query->set_404(); status_header(404); } } add_action( 'wp', 'productsPageRedirect_404' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, 404 error" }
add_rewrite_rule issues i usually add rewrite rules for custom pages like this: add_rewrite_rule('^deal-purchase?','index.php?is_purchase_page=1&post_type=page','top'); However on a site im working on now, the above just redirects to the home page whereas if i create a custom post type and reference that: add_rewrite_rule('^deal-purchase?','index.php?is_purchase_page=1&post_type=market','top'); it works. Anyone any ideas what might be causing the 1st code to fail?
The second one works because `post_type=market` triggers the market post type archive. Pages have no archive, so `post_type=page` in the first example doesn't point to a valid destination. Rewrite rules have to ultimately result in a successful main query. For a specific page, you could use `page_id` or `pagename`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rewrite rules" }
Function/filter or plugin to change post status based on custom field value I am looking for a way to change the post status of some posts based on custom field value, from published to pending for example. How might this be possible? My solution: $post_ids = array( 1235, 1234, 1228, 1221, 1211, 1212, 1208, 1200 ); foreach($post_ids as $post_id) { $post = array( 'ID' => $post_id, 'post_status' => 'pending' ); wp_update_post($post); }
Paste this onto any page and load the page (or make it a function in functions.php and call that function somewhere) $args = array( 'nopaging' => true, // Loop through all posts at once 'meta_key' => 'YOUR_CUSTOM_FIELD_NAME', // Replace with the name of your custom field 'meta_value' => 'YOUR_CUSTOM_FIELD_VALUE', // The value of that field you're matching for ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); // Change the status of each post to pending $updated = wp_update_post( array('ID' => $the_query->post->ID, 'post_status' => 'pending' )); // Check to see if loop is returning posts, and if they were updated echo 'Post #' . $the_query->post->ID . ' - ' . $updated; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, post status" }
How do I embed in a text widget? I'm trying to embed a YouTube video in a Text Widget and Wordpress 4.0 is stripping out the embed when rendering. For example, if I put this in the body of the widget: Before [embed] After then when I inspect the div in the browser I end up with this: <div class="textwidget">Before After</div> How can I get Wordpress to keep the embed in the widget?
Shortcodes are not supported in the Text Widget by default. Add the following to your functions.php: // Enable shortcodes in WP Text Widget add_filter( 'widget_text', 'shortcode_unautop'); add_filter( 'widget_text', 'do_shortcode', 11); Instead of wrapping the video URL in the [embed] shortcode, use the following in the Text Widget: [video src=" For more info on the [video] shortcode, see the Codex.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "widgets, embed" }
If product is in sub-category show code This code works with categories but not with child sub-categories. How can I make it work a child category that is not in the url (slug)? global $post; $terms = wp_get_post_terms( $post->ID, 'product_cat' ); foreach ( $terms as $term ) $categories[] = $term->slug; if ( in_array( 'lucha', $categories ) ) { echo '<div class="nota-categorias-especiales">Important: this product has special conditions. <button class="single_add_to_cart_button button alt" type="submit">Contact Us</button> </div> '; } else {} ?>
You can probably just make use of `has_term( $term, $taxonomy, $post )` which will check if the specific post belongs to the term given You can do something like this ( _Edit: Add post ID if this is used in a function_ ) global $post; if(has_term( 'lucha', 'product_cat', $post->ID )) { //do something if post has lucha term }else{ //do something else if the post don't have lucha term }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "terms, children" }
How to Make admin Sidebar Menu always be Collapse by code I have solution with js that click on the Collapse button, but this is no good solution. I want to make this work true DB with php code. I found that the table who hold this value is `wp_usermeta`. Then there is a column [`meta_key`] that hold: `user-settings` and there is column `meta_value` that hold values for example: `mfold=o&editor=tinymce&libraryContent=browse&ed_size=465`. The value that I need is `mfold=o` so I want to check if "mfold" not exsist then add mfold=1, else check if mfold=o update to mfold=1 I've tried to play with <?php get_user_meta($user_id, $key, $single); ?> and <?php update_user_meta( $user_id, $meta_key, $meta_value, $prev_value ); ?> but without luck
To make the admin sidebar menu always be collapsed, try adding the following code in the `functions.php` file of your child theme, or add it in your site using a plugin like Code Snippets, or Add Actions and Filters. global $user_ID; $user_fold = get_user_meta( $user_ID, 'wp_user-settings', true ); $exp_array = explode( "&", $user_fold ); $search_array = array_search( "mfold=o", $exp_array ); if ( $search_array ) { $exp_array[ $search_array ] = "mfold=f"; $exp_array = implode( "&", $exp_array ); update_user_meta( $user_ID, 'wp_user-settings', $exp_array ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user meta, buttons" }
Get posts with multiple categories How to get just the common posts of 2 different categories? consider this category tree: posttype -news -arrangement --course --competetion --other region -region1 -region2 -region3 Now I want to get the posts in categories 'news' and 'region2'. I have tried this: $query = new WP_Query('category__and=12,32'); // 12=news, 32=region2 But then I get all the posts which have either category 12 or category 32. I want those posts which have both 12 and 32.
`category__and` needs to be an array of category ID's > **category__and** (array) - use category id. You can modify your code to look like this $query = new WP_Query( array('category__and' => array(12,32)));
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, wp query" }
wp_update_post question on array How can I run the wp_update_post function on an array of post ids.It doesn't seem to respond to an array although I don't get an error and only seems to work for one? $post_id = array(1235,1234,1228, 1221, 1211, 1212, 1208, 1200); $post = array( 'ID' => $post_id, 'post_status' => 'pending' ); wp_update_post($post);
`wp_update_post` expects 'ID' to be a single post ID, not an array. You will need to handle each post separately. Try: $post_ids = array( 1235, 1234, 1228, 1221, 1211, 1212, 1208, 1200 ); foreach($post_ids as $post_id) { $post = array( 'ID' => $post_id, 'post_status' => 'pending' ); wp_update_post($post); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts" }
is_page Funtion for Posts ? I am using a plugin Bottom of every post which have a a function `if( !is_page( ) && file_exists( $fileName )){` which is printing custom Text on bottom of every pages, i want to show them on **pages not on the posts** , can anyone suggest me a function or a way to complete this job ? Any suggestion would be appreciable.
Remove the ! before `is_page()`. The function `is_page()` is built into WordPress and only tests if the post being viewed is a page or not. The `!` stands for "not", so if you take it out, the code will only return true on that part if it is a page.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, functions, pages" }
Removing a page from the header menu My site is using the Hemmingway theme, I have a menu in the header. This is the menu whose structure results from assigning a "parent" on a page's edit form. One of my pages is less important and should not appear in the menu. (It is accessible through links from the body of other pages.) I went to Appearance->Menus (/wp-admin/nav-menus.php) and removed this page under the Menu Structure list (there is only one menu there, "Menu 1". Yet this page still appears in the header menu. How do I remove it from the header menu?
I manually created a menu under Appearance->Menus and then assigned this as the Primary Menu. This worked, but required me to manually reproduce the structure of the menu: The structure created by assigning a parent in each page's admin is now simply ignored. I would still like a way to use the default menu, which is generated straight from the parenthood relations, yet make modifications like omitting a page from the menu.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
the_title not working I'm using `the_title()` to show the title of a custom post type, but it's not working; the title does not show. get_header(); $wp_query = new WP_Query(); $wp_query -> query('post_type=press&showposts=20'); while ($wp_query->have_posts()) : $wp_query->the_post(); ?> <div class="press-item"> <div class="press-img"><?php the_post_thumbnail('medium');?></div> <div class="press-content"> <div class="press-title"><?php the_title(); ?> </div> <div class="press-excerpt"><?php the_excerpt(); ?> </div> </div> </div> <?php endwhile; get_footer();
Try this as your query: $args = array( 'post_type' => 'press', 'posts_per_page' => 20 ); $wp_query = new WP_Query( $args ); while // etc. Also you could try: <div class="press-title"><?php echo get_the_title(); ?> </div>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, get the title" }
Cannot use some themes within Managed WordPress of Go Daddy Some themes display blank pages instead of my home page when I activate them.
Check to see if you have set up your site to use a specific static page as the site home page and another as the blog home page. If you haven't, the default is to show posts on the site home. Next check to see if the themes include both index.php and home.php. Typically home.php is used for the home page of the blog, and index.php for the site home page with page.php being used for internal pages. If your site requires one of these templates and it isn't there, that could be the problem. Generally if home.php isn't there, then WP falls back on index.php. If that is the case then you want to look at index.php to make sure if is using the right WordPress loop. If you compare the files between a theme that works and one that doesn't that should help you isolate this problem. Good luck.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "themes" }
pre_get_posts not firing at all I'm trying to add a custom post type into the seach facility so that it searches those posts as well as the pages on a site. I have seen the pre_get_posts function and have it set up like the below in my themes functions.php file but its not firing at all. I have put get_current_screen() function in there to test but it doesn't return anything. function searchAll($query) { if ( !is_admin() && $query->is_main_query() ) { if ($query->is_search) { $query->set('post_type', array( 'post', 'movie' ) ); } } } add_action('pre_get_posts','searchAll'); I also tried to just have the $query->set('post_type', array( 'post', 'movie' ) ); line not in any of the if statements but nothing is happening. What am I doing wrong? Please help!
Try adding this to your functions.php. function my_custom_get_posts( $query ) { if ( is_admin() || ! $query->is_main_query() ) return; if ( $query->is_search() ) { $query->set( 'post_type', array( 'post', 'movie' ) ); } } add_action( 'pre_get_posts', 'my_custom_get_posts', 1 ); Also make sure you do not have any other `pre_get_posts` action overwriting this function's effect.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, search, pre get posts" }
Uncaught TypeError: number is not a function <script type="text/javascript" charset="utf8"> jQuery('img').each( function($) { var mySrc = $(this).attr( "src" ); $(this).before( '<a href="' + mySrc + '" class="link">' ); $(this).after( '</a>' ); }); </script> Hello, I can´t make this code work, and I don´t know why... I am trying to add a link to every image of my site, and it is located just before the I am really bad with Javascript/Jquery so please any help/feedback would be really appreciated :) Thanks!
Try this: <script type="text/javascript" charset="utf8"> jQuery(function($){ $('img').each( function() { var mySrc = $(this).attr( "src" ); $(this).wrap( '<a href="'+mySrc+'" class="link"></a>' ); }); }) </script>
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "jquery" }
How to reset (clear) theme settings I'd like to reset (clear) theme settings (from customizer) while activating theme. For example a theme by default has red menu, links and links on hover. I use something like this: function clear_prefs( $theme_name ) { global $wpdb; $table = $wpdb->prefix . 'options'; $wpdb->delete( $table, array( 'option_name' => 'menu_sidebar_color' ) ); $wpdb->delete( $table, array( 'option_name' => 'link_color' ) ); $wpdb->delete( $table, array( 'option_name' => 'hover_color' ) ); } add_action("switch_theme", "clear_prefs"); But maybe there is more elegant and correct (standart for WP), not so 'rough' way?
I've found the solution, maybe it'll be useful to anyone: function reset_mytheme_options() { remove_theme_mods(); } add_action( 'after_switch_theme', 'reset_mytheme_options' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "theme options, theme customizer" }
HTTP Error when trying to upload image I'm getting an `HTTP error` when trying to upload an image. The image is 6MB, yet I was able to upload a 10MB image just previously. I set the following, but they did not help: define('WP_MEMORY_LIMIT', '64MB'); define('WP_DEBUG', true); # could not start the upload post_max_size = 12M # php.ini upload_max_filesize = 12M # php.ini max_input_time = 120 # php.ini I restarted `httpd`. There is no message in `httpd/error_log`. I have Wordpress 4.0, and PHP 5.3.3. None of the following answers were helpful. How to Fix HTTP Error When Uploading Images? "HTTP error" randomly on image uploads HTTP Error when uploading images
I updated PHP to 5.3.3-38 (el6) and that seemed to fix it for now.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, uploads" }
What do you put in child themes author tag? What is the common practice in authoring child themes ? I mean, if I make child theme of some free theme should I put myself as author or should I keep the name of the original themes author ? I searched quite a a bit but unfortunately couldn't find clear answer.
There are several scenarios: 1. If you had authored your child theme from scratch, using only your custom code then it is clearly **your** product. 2. If you had used code from parent theme in your child theme then it's **your derivative** of it, it's still yours but you **also** need to credit code used in line with its licensing requirements. 3. If you had taken third party child theme and modified it you usually choose between **keeping authorship and noting your modifications** (usually for private or semi–private use) or **renaming it** and treating it as derivative same as 2 (usually if you intend to distribute publicly). In either case pay close attention to licensing requirements of original theme.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "author, child theme, copyright" }
Moving meta boxes in admin I have added tags to my custom post type and by default the tag meta box appears under the 'publish' meta box on the right. I can manually drag the meta box to reposition it under the rest of my meta boxes on the left but this is inefficient in deployment. How can I position the default tags meta box using code like the rest of my meta boxes? add_action( 'admin_init', 'admin_boxes' ); function admin_boxes() { add_meta_box( 'display_text_meta_box', 'Text box', 'display_text_meta_box', 'custom_types', 'normal', 'high' ); } function display_text_meta_box( $custom_type ) { }
You can remove the default post tags metabox and then add it again in the desired location, ex: add_action( 'add_meta_boxes', 'move_tags_metabox_location', 0 ); function move_tags_metabox_location(){ global $wp_meta_boxes; unset( $wp_meta_boxes['post']['side']['core']['tagsdiv-post_tag'] ); add_meta_box( 'tagsdiv-post_tag', 'Tags', 'post_tags_meta_box', 'post', 'normal', 'core', array( 'taxonomy' => 'post_tag' )); }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "custom post types, metabox" }
Static image for embedded YouTube video instead of blank player? Thanks to this answer I have embedded a YouTube video in a Text Widget using [video src=" However it displays as this blank player when the page is loaded: !Blank YouTube player I've tried adding a `&start=1` to get it to show the first frame of the video but that doesn't have any effect. How can I get this embedded player to show a still from the video instead of this blank player?
Try adding another attribute [video src=" poster="/path/to/image-placeholder"] See the Codex
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets, embed, youtube, video player" }
Show button if meta box has content, else hide I have a meta box setup that allows the article creator to post a link to the forum topic of the same article subject. I display this meta data with the following: <div class="discuss"> <a href="<?php echo get_post_meta( $post->ID, 'true_title', true ); ?>">Discuss...</a> </div> Is there an `if` statement I could use so that if there is meta data to display, then it shows the button, but if not, it simply removes the button?
Check to see if it's empty before you show the div. <?php $true_title = get_post_meta( $post->ID, 'true_title', true ); ?> <?php if( ! empty( $true_title ) ) : ?> <div class="discuss"><a href="<?php echo $true_title; ?>">Discuss...</a></div> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "metabox" }
Prevent Google from indexing custom post types? I am using custom post types to add certain sections to my website. These post types are not meant to be treated like a blog, it's basically just an easy way for me to give the client access to managing certain sections, such as "reviews." Today I noticed that Google is indexing these custom post types and I was wondering how I can prevent that. For instance, "reviews" is one of my custom post types and Google is indexing mywebsite.com/reviews as well as mywebsite.com/reviews/review, which looks terrible because there is no layout for it. Is there any way to prevent Wordpress from even creating these sections? Thanks!
If you write code for registering custom post-type try adding these attributes public => false, has_archive => false, publicly_queryable => false, query_var => false Otherwise, set these options to false in plugin that you might be using.
stackexchange-wordpress
{ "answer_score": 11, "question_score": 5, "tags": "custom post types" }
How to display different number of posts How do I display different number of posts on the home page and archive pages, the archive pages can use the value set in the admin, but I want a custom number of posts to be displayed on the home page with pagination. Thanks.
This can be done with a very short plugin. function posts_on_home_page( $posts_per_page ) { if ( is_home() ) return 5; return $posts_per_page; } add_filter( 'pre_option_posts_per_page', 'posts_on_home_page' ); This is actually pretty close to the Codex example for `pre_option_(option_name)`).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, loop, pagination" }
Where is this folder I am very very new to wordpress. I had a company set things up for me and now I am broke...so I am trying to make changes on my own. I figured most stuff out, but I cannot find out how to access the image folder for the header of my site...I want to replace it with a new image that I am making. When I click on the image and ask for the source it tells me that it is located here: < But I logged into my wordpress account and I cannot find that folder anywhere. Please help!
You would need to connect to your webserver via FTP, and navigate to that folder. That folder is not accessible via the WordPress admin utilities.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
Ordering WP_User_Query results by the user IDs used in the include parameter I'm using `WP_User_Query` to bring back a list of users. I'm passing a list of specific users to be included in results. For example: $user_ids = array( 1, 5, 9, 61, 24, 12 ); $args = array( 'include' => $user_ids, 'count_total' => true, 'search' => sanitize_text_field( $_GET['phrase'] ) ); $query = new WP_User_Query( $args ); Results are currently ordered by `user_login`. How can I modify my query so that the results returned are ordered by my `$user_id` array? For example, if 3 users are to be returned (let's say IDs 5, 61 and 12), then user 5 should be displayed first, user 61 second and user 12 third. Ref: <
I think that instead of dealing with complex SQL queries and ways to make WordPress use them, a simple `uasort` can do the trick: $uids = array( 1 ); $user_query = new WP_User_Query( array( 'include' => $uids ) ); $users = (array) $user_query->results; usort( $users, function( $a, $b ) use( $uids ) { return array_search( $a->ID, $uids) < array_search( $b->ID, $uids ) ? -1 : 1; } ); // use as usual foreach ( $users as $user ) { echo '<p>' . $user->display_name . '</p>'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp user query" }
Link from navbar to categories I have a navigation bar in homepage. I don't want show categories in navigation bar. I also do not want use a dropdown menu. I just want to have a link to a page that show all categories. !enter image description here I want when clicked a link in this case categories, my categories show like below: !enter image description here but don't know do it. Any suggestions?
To show all categories on a page, you will have to create a new page template. <?php /** * Template Name: Categories Page **/ get_header(); ?> <!-- content --> <div id="content"> <ul class="category-list"> <?php wp_list_categories( 'title_li=' ); ?> </ul> </div> <!-- / content --> <?php get_footer(); Now create a new page for categories in WordPress admin and select this page template `Categories Page` from template list. And add this page to your menu. That's it. Of course you will have to create CSS styles for appearances.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, menus, links" }
Custom-Post-Type - how can I get the only post by IDnumber? I´m a PHP noop and I want to get the post from a post_type with a specifically ID(for example 64), and than only this.. For Example if there are 3 posts in my post_type (ID 63, ID 64, ID 65) than please show me in frontend the post with ID 64.. Can you help me? I try this >>> $args = array( 'post_type' => 'my_pt_name'); $query = new WP_Query( $args); $my_postid = 64; $content_post = get_post($my_postid); $content = $content_post->post_content; $content = apply_filters('the_content', $content); while ( $query->have_posts() ) : $query->the_post(); echo $content; endwhile; But in this case, it show me all posts too???
You query is completely wrong and mingled. You are using `WP_Query` and `get_post` together and intermingled in one query, which will never work To retrieve just **one** single post, make use of `get_post`. You can delete your complete query in your question. Replace it with something like this <?php $post_64 = get_post(64);  echo $post_64->post_title; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Add javascript to a woocommerce page template I have the following code in my `functions.php` add_action( 'wp_enqueue_scripts', 'dc_datepicker_options' ); function dc_datepicker_options() { if ( is_page_template( 'single-product.php' ) ) { $ss_url = get_stylesheet_directory_uri(); wp_enqueue_script( 'datepicker-options', "{$ss_url}/js/datepicker-options.js" ); } else { // Returns false } } I'm trying to call `datepicker-options.js` only on my product pages. But it doesn't seem to be calling it.
There is Woocommerce conditional tag for single product page Try if(is_product()) instead of if ( is_page_template( 'single-product.php' ))
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "javascript, woocommerce offtopic" }
How to add extra language packs to WordPress I've got a multisite which I installed in Dutch. Therefore English and Dutch are available in the general settings tab. But I need to add German and French. I can't select any other language from the drop down. And if I add a language in the `wp-config.php` it just gives a notice without any direction. Of course I googled but I can't seem to find anything useful. How can I active an other language and download the `.PO`/`.MO` files? * < * <
1. The easiest way for me is to change language settings for main blog multiple times (as mach as many languages I need) and WordPress will load these languages automatically. 2. And after that I go to Update page and update language packages (loads languages for themes, plugins, etc.)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "translation" }
Mq translate plugin custom post type issue I am using a < theme. I use mqtranslate plugin to translate my site in two language english and chinese. Mqtranslate allows the admin to create categories and posts in mulilanguages in the backstore. It also allows the admin to write the job in mulilanguages. But it gives no access to writing the job categories in mulilanguages. I need this feature coz the job categories are shown in the homepage - i need them switchable between language with the site. I believe it is a easy fix. Job is a custom post type, there is a problem with custom post type category.
MQtranslate is a fork of Qtranslate so the hooks should be the same, and to get Qtranslate to Work in custom taxonomies I use this: /** * qtranslate custom taxonomies */ function qtranslate_edit_custom_taxonomies(){ $args=array( 'public' => true , '_builtin' => false ); $output = 'object'; // or objects $operator = 'and'; // 'and' or 'or' $taxonomies = get_taxonomies($args,$output,$operator); if ($taxonomies) { foreach ($taxonomies as $taxonomy ) { add_action( $taxonomy->name.'_add_form', 'qtrans_modifyTermFormFor'); add_action( $taxonomy->name.'_edit_form', 'qtrans_modifyTermFormFor'); } } } add_action('admin_init', 'qtranslate_edit_custom_taxonomies'); this should work for you as well.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, custom post types" }
Save re-arranged draggable post items to wordpress database So i've followed the clearly documented pages for the packery and the draggabilly plugins to allow for a customizable grid and looked at how localStorage can be used to remember/store data of the re-arranged order of items upon reload. So it works fine on the front end, closely following this example. How would one go about saving this data to a wordpress database? Can one use localstorages data structure to put the updated post order into the db (so mainly a HTML5 and js solution)? Are there any wordpress functions that would aid with this customisation (possibly resulting in more of a PHP solution)?
You would have to do the following to save the order data into the WordPress DB, 1. Do a WordPress AJAX sending the data that you want to be stored in it. You can do it at every re-arrange event of the elements. 2. Handle the AJAX call in PHP and either do an update_option() or an update_user_meta() to save the data.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, post meta, html5" }
Change "en-US" to "en" Hey I am trying to edit the WP theme files, and I am using `bloginfo('language')` to get the language of the page. However, it returns me "en-US", which does not work while redirect the page. The site I am working on only accept "/?lang=en". I have tried to use if statement to specify the solution under different situations, but it failed, it seems the theme used a complex loop method, a slightly change will make the functions does not work. So could I ask if there is an alternative way to transfer "en-US" to "en", or get "en" directly from the browser? Thank you.
If you want to get the language of the browser do so: $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); If you want to redirect to `?lang=en`: header("location: {$_SERVER['REQUEST_URI']}?lang={$lang}"); You should read about **HTTP_ACCEPT_LANGAUGE**. There are many ways you can _dance_ with languages but you should understand some key points. 1. Chose the default language of your website (French in your case) 2. The user may be French but his OS & Browser can be in English because he wants to learn the language of trade. 3. Create a cookie that stores the selected (or default) language so that you know what content to display. `$_COOKIE["wpse_166976_lang"] = "fr"` or `$_COOKIE["wpse_166976_lang"] = $land` where `$lang = get_query_var("lang")` To get the language with **WPML** plugin, you could use `ICL_LANGUAGE_CODE` to get the language of the page
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "php, multi language, bloginfo" }
How to migrate .HTML pages to WordPress I have a site I want to move into WordPress. Currently, each of the site's pages reside in the document root and end in `.html`. For example: Home Page = index.html About Us Page = about.html etc. When I Add New Pages in WordPress, the permalink for the about us page (for example) gets created as /about-us/ How do I code WordPress to make the `About Us Page = about.html` I do not want to lose SEO status, indexing, etc.
For posts there even is an easy way to change this in the backend: > Settings → Permalinks !Permalink Settings Codex: Permalink Settings The problem is that for pages this isn't a built in feature. Here is another question that might give you a hint: Add .html (dot HTML) extension to custom post types The reasons why I proposed using redirects instead of changing the permalink structure are: * You stay within defaults in WordPress which avoids unwanted side-effects and always makes it easier later on. * Non-html URLs are more common nowadays (and more beautiful if you ask me, but this of course is a matter of taste) In case you decide to go the redirect route you can add this to your `.htaccess` file: RewriteRule (.+)\.html$ /$1/ [L,R] Source: htaccess redirect all html files
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages" }
How to sort results from a custom database table I've created a custom WordPress database table which I'm using to store 'likes'. The columns I have are: * id * post_id * user_id I'm now trying to get an array of post IDs that a particular user has 'liked'. So far I have this: $my_array_of_post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT post_id FROM like WHERE user_id = %d", $user_id ) ); How can I ensure my `$my_array_of_post_ids` array is sorted so that the most recent 'like' is the first item in the array, the second most recent 'like' is 2nd, the third most recent 'like' is 3rd and so on?
Don't you mean this query: "SELECT post_id FROM like WHERE user_id = %d ORDER BY id DESC" where we assume that the `id` column is unique and increase with each _like_.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, database, query, mysql" }
"next_posts_link" and "previous_posts_link" display me NOTHING I'm trying to add links "Previous Post" and "Next Post" in my single.php file without success because previous_posts_link and next_posts_link dont return anything. Honestly I do not know where in the loop put these buttons. Thanks. <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div class="post-content"> <?php the_title(); the_content(); ?> </div> <?php endwhile; ?> <ul class="nav-posts"> <li class="prev-link"><?php next_posts_link('« Previous Post') ?></li> <li class="next-link"><?php previous_posts_link('Next Post»') ?></li> </ul> <?php endif; ?>
`next_posts_link` and `previous_posts_link` (plural) are for archive pagination. For single posts you want `next_post_link` and `previous_post_link` (singular).
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "posts, single, next post link, previous post link" }
Date format - Meta Box plugin I am getting a date using the plugin Meta Box. The output is: " **2014-10-30** " and i'd like: " **30/oct/2014** " There is a way to change the default format? This is the register of the metabox: $prefix = 'ns_'; 'fields' => array( array( 'name' => 'Evento', 'id' => $prefix . 'event_date', 'type' => 'date', ), And i'm calling it this way: <?php echo rwmb_meta( 'ns_event_date' ); ?> Thanks!
Probably but this would be using a PHP function along the lines of, $metadate = rwmb_meta( 'ns_event_date' ); $date = new DateTime($metadate); echo $date->format('d-M-Y');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, metabox, post meta" }
jQuery post method in admin menu I'm trying to use this: jQuery(document).ready(function(){ jQuery("#button").click(function(){ jQuery.post("post_file.php") }); }); on this: myaddress.com/wp-admin/admin.php?page=pluginname/pluginfile.php_pluginfunction but what happens is that it opens this: myaddress.com/wp-admin/admin.php?variables How can I make it stay in plugin's function ?
I guess I'm just too tired. This helped: <input type = "hidden" name = "page" value = "pluginname/pluginfile.php_pluginfunction " />
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery, admin menu" }
exclude particular posts in archive.php My archive file contains.. <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a> But i want to exclude few posts with their ids, how can i do that ? Important! But those excluded posts should display in the Google search as normal, i don't want to loss them in the search engines. Just i want to hide in my site only. Thank you friends.
You can exclude posts from archive pages with thee help of `pre_get_posts` action. Usually `pre_get_posts` is used to modify main query, so it's best solution for your problem. function my_custom_get_posts( $query ) { if ( is_admin() || ! $query->is_main_query() ) return; if ( $query->is_archive() ) { $query->set( 'post__not_in', array( 7, 11, 21 ) ); } } add_action( 'pre_get_posts', 'my_custom_get_posts', 1 ); Please notice `7, 11, 21` in above code, these are the post IDs we are excluding from archive pages. You can specify as many comma separated post IDs as you want. Yes, it will not prevent Google to index them.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "posts" }
W3 Total Cache: Load CSS asynchronously for better PageSpeed score? I'm using W3 Total Cache to minify about 15 CSS files, and also to minify 20 JS files and load those asynchronously in the footer. Running my site through PageSpeed gives me the following message: > Eliminate render-blocking JavaScript and CSS in above-the-fold content What I'm wondering is, how can I load this CSS file asynchronously with W3 Total Cache? The plugin doesn't give me the option to load CSS asynchronously. You can see how things are loaded on my site here.
Have much to say about both W3TC and pagespeed, but will try to stay on the point. You should never have a JS external element in you HTML as part of the actual content, they should be either in the head element (but only scripts that must be loaded before the page finishes loading) or just before the end of the body. CSS should be only in the head element. The assumption is that if you decided to violate those basic performance rules you probably had a very good reason for that, and no plugin with a sane author will try to rearrange it for you as you can easily break the page if things are not being loaded in the right order. So you need to understand first why do you have JS and/or CSS at that part of the page, and if it is not needed then you need to change your code to move them to the header or footer. Caching plugins have totally nothing to do with it and should stay away from even offering page changing functionality like that.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, css, javascript, cache, plugin w3 total cache" }
Is this spyware on my site or a real Java update? I run a small WordPress website for the wife < I keep getting this java update box poping up only on her site and looking at the links they go to somesite ppv2014.info which can't be real Now my question how can I track this down and remove it? I've had a good look in the files for her site but can't seem to find it. In case you do not see the pop up this is what I see. !enter image description here
There's an iframe injection according to the source code: `<iframe src=" style="min-width:100%; min-height:100%; height:100%; width:100%; max-width:100%; max-height:100%; overflow: auto; border:none;" frameborder="no"></iframe>` It seems to be enclosed in a div called "pop": `<div class="pop" id="pop" style="position: fixed; z-index: 100002; border: 4px solid rgb(0, 0, 0); height: 60%; width: 60%; top: 20%; left: 20%; background-color: rgb(255, 255, 255);">...</div>` My best guess is that you have an extension that has been compromised. Disable extensions one by one until it disappears. Failing that, change the theme to see if it's an infected theme. And failing that, back up the Wordpress database and reinstall it.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, html" }
Custom Post type as Taxonomy I have a custom post type "issue" and relationship with custom post type "article". What I want is, to create the issue cpt as a taxonomy for the article cpt, and showing it in article post list. When the users add new issue, so the taxonomy will updated it self. And the final result is, I can filtering the articles only based on the issue name. Anyone can help?
I found the solutions for this, finally i filtering the custom post type by custom type no need to create or converted post type to taxonomy :)
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "custom post types, custom taxonomy, custom field" }
Update custom post type title I want to update the post meta of a custom post type when a user updates the custom post type's title in the admin backend. Something like the pseudo code below; if ((get_the_title() !== $val_in_title_field) && (Publish == true)) { update_post_meta( $id, 'custom_field', '' ); } I am not clear on how to check what is passed from the title field when a user clicks publish and all how to check if a uer has clicked publish.
Try this out, add_filter( 'wp_insert_post_data' , 'modify_post_title' , '50', 2 ); function modify_post_title( $data , $postarr ) { if($data['post_type'] == '{custom post type}') { if($data['post_title'] == $postarr['post_title']){ update_post_meta( $data["ID"], 'custom_field', '' ); } } return $data; } Reference: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Custom Post Type Fields I am very interested in creating a coupon plugin for Wordpress, where many of the existing options do not meet my current needs. I have build the core plugin and it is working as expected now so I feel like I am getting close to accomplishing this task. The problem is that I would like to implement custom fields into the plugin and have them easily set by the authors. These would be things like coupon code, discount amount, expiration date, etc. This plugin (coupon creator) seems to have the layout I am looking for on the Post page, but I have been unable to figure out how its done, where these do not appear to be the "Custom Fields" shown in other tutorials. How would I go about replacing the large WYSIWIG Editor box with fields like this instead for my CPT? !enter image description here
You can do this by not including "editor" in the "supports" argument. And then add a new meta box using add_meta_box() in whose call back you can add all the post meta's as required.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, custom post types, custom field" }
admin edit link from a specific page When I am not logged in my WordPress site, suppose I am in a page like: Is there any way that I can create a direct link to the edit admin page for this specific 'pagename'? For example, something like which of course will require first admin login.
I am not sure I completely follow your second example. You can use `get_edit_post_link()` template tag, which will output the link to admin side for the current post (only for users who _can_ edit the post). If you just want _pretty_ link for that there is no native way, but it looks similar to what Slash Edit plugin does.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin" }
$wpdb - do you have to use foreach even if there will always only be one result? I have a $wpdb query that will always **only** return one result. This is a simplified version of it: $results = $wpdb->get_results ( "SELECT name FROM testTable WHERE id=1" ); Do I have to use foreach to get that single result? foreach ($results as $result ) { $name = $result->name; } Or can I skip the foreach and instead do something like this: $name = $result->name[0];
Read the Codex: > The `get_var` function returns a **single variable** from the database. Though only one variable is returned, the entire result of the query is cached for later use. Returns **NULL** if no result is found. <?php $wpdb->get_var( 'query', column_offset, row_offset ); ?> So for you its: $name = $wpdb->get_var("SELECT name FROM testTable WHERE id=1"); If you want a row use `get_row`: > To retrieve an entire **row** from a query, use **get_row**. The function can return the **row** as an **object** , an **associative array** , or as a **numerically indexed array**. If more than one row is returned by the query, only the specified row is returned by the function, but all rows are cached for later use. Returns NULL if no result is found, consider this when using the returned value in arguments, see example below.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "wpdb" }
How to create a specific Web App with WordPress? Can we make Web Apps in WordPress with specific (custom) scope, something like a mini-Facebook, a mini-Twitter, a stackoverflow, etc. What I really want to know is that how much am I free handed to build whatever Web App I want in WP? and more importantly how to?
Yes, of course you can make any type of web app. Use **Page Templates** for different pages, **Custom Post Types** for different data handlers, **Taxonomies** for categorizing those data, and **Plugins** for advanced functionality. WP Codex is best way to dive into WordPress.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "third party applications" }
How can I automatically resize up images to fit into all of my registered image sizes I need Wordpress to create versions of each image in ALL of the registered image size, even if the registered image size is larger than the uploaded file. For example, if I have the following registered image sizes: * large: 1024x1024 * medium: 800x600 * my-custom: 645x200 and I upload a an image of the dimensions 200x200, I need the system to scale the image up and crop it into all of the image sizes. How would I go about doing this? Or is there a plugin somewhere that could do it for me?
What you are asking for is called "upscaling images". Wordpress does not do that by default (with reasons). 2 solutions: 1. no physical upscaling: display your images via CSS (and not as IMG html tags), using `background-size: cover;` 2. a plugin that upscale images. Here is one (untested).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, images" }
Insert Image automatically when upload finishes wordpress media uploader What I am trying to do is - 1) User clicks "Add Media" 2) Select an image 3) Image uploads finishes 4) Now it should insert into post automatically without pressing "Insert into post". Anywhere to hook, and click the "Insert into post" using jquery. Any clues ?
The hook for doing stuff after an upload is the `reset` event on `wp.Uploader.queue` triggered by the pluploader when it's finished (see line 249 in "wp-includes/js/plupload/wp-plupload.js"). Here's one hack to use this to do an auto-insert after an upload: function wpse167143_admin_footer() { ?> <script> jQuery( document ).ready(function() { typeof wp.Uploader !== 'undefined' && wp.Uploader.queue.on( 'reset', function () { // From the primary toolbar (".media-toolbar-primary") // get the insert button view (".media-button-insert") // and execute its click (as specified in its options). wp.media.frame.toolbar.get('primary').get('insert').options.click(); } ); }); </script> <?php } add_action( 'admin_footer' , 'wpse167143_admin_footer' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "uploads, media" }
Change sidebar product category text color (woocommerce) I have woocommerce shop set up here: < I am trying to change the color of the category texts to black in the left sidebar, however I've been unsuccessful so far even trying various CSS tweaks. Currently there is "Men" and "Women", which is the text color I would like to change to black. I'd appreciate any input. Thank you.
In your particular case you need to change your CSS: .widget ul li a { color: black; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "css, sidebar, woocommerce offtopic, text" }
Return array keys and values I am creating some options in the functions.php file. I created a function that gets input on the front end, puts the values into a new array and returns them to the front end. I am trying to figure out how to return the values like an associative array. For example, I want to the array to return like this Array ( [dribble_id] => dribble [google_id] => google [facebook_id] => facebook [twitter_id] => twitter ) the below function returns them like so Array ( [0] => dribble [1] => google [2] => facebook [3] => twitter ) Here is the function that returns them function ritual_get_options() { $arg_list = func_get_args(); $options = array(); foreach( $arg_list as $key => $value){ $options[] = ot_get_option($value); } return $options; } Do you now how I can do this?
This is not really a Wordpress question but more PHP. To solve this problem, you need to use `$value` as your key as well plus `_id` You can do something like this $options[$value . '_id'] = ot_get_option($value); **EDIT** If you need `$key` to be the value of `id`, you can also try something like this $options[$value . '_' . $key] = ot_get_option($value); This will render something like google_0 => google google_1 => google google_2 => google
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "array" }
How to leave a line between paragraphs when writing text in the visual or text editor I'm using the inbuilt text editor in Wordpress 4.0 to edit some content. I've got 2 paragraphs and would like to leave a blank line between the two. To do this I could add a `<br>` element between the 2 paragraphs, but if someone who doesn't know html is writing the content this wouldn't be very helpful; is there a way it can be done natively in Wordpress? I've attached some markups to illustrate the issue at the moment. !enter image description here !enter image description here !enter image description here
You should use wpautop, and in your CSS styles (editor styles + theme styles) make sure that any paragraphs are properly spaced. p { margin-bottom: 20px; } or p + p { margin-top: 20px; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "editor, cms" }
Redirect to page 2 after comment I would like to have commenters going to the page 2 of a paginated post. My posts are separated by the `<!--more-->` tag so i have the `www.site.com/post-title` and `www.site.com/post-title/2/`. I want users to visit the second part of the post after commenting. I found other questions explaining how to move the user to the paginated comment, that is `www.site.com/post-title/comment-page-x/#comment-x` but not to other pages of a paginated post. **Edit:** My site has the common setting for permalink that is `wpinstallation/%postname%/`. When paginated, it becomes `/%postname%/2/` for page 2. Thanks.
After reading a bit on regex and preg, starting from a previous example of a similar problem and testing it I was able to answer my own question. I added this function to functions.php: <?php /** Plugin Name: WPSE (#167237) Redirect after comment */ add_filter('comment_post_redirect', 'redirect_after_comment'); function redirect_after_comment($location) { return preg_replace("/comment-page-([\d]+)\/#comment-([\d]+)/", "2", $location); } It's replacing the part of the url stating the comment page and comment anchor with "2". It may not be the cleanest solution but it's how I managed to do as a beginner.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "comments, pagination, redirect, read more, split" }
Show only one level in breadcrumbs I'm looking for a WordPress way to remove current and all grandparents from breadcrumbs. Basically, functionality is identical to history back button, but with page title. Don't want to do this in JS for obvious reasons. Any ideas? Cheers!
You can use wp_get_post_parent_id to return just the parent ID of the page in question. Then you can use get_the_title and get_permalink with that parent ID to build a back button to the parent page; <?php if( $parent = wp_get_post_parent_id( get_the_ID() ) ): ?> <a href="<?php echo get_permalink($parent); ?>"><?php echo get_the_title($parent); ?></a> <?php endif; ?> Something like this should work. Unable to test this but it should be fine. Alternatively you could get the entire post parent with get_post and bring out the data you need that way but that is probably more CPU intensive for such a simple thing as getting a link.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "breadcrumb" }
Display only post types that are direct children of the current taxonomy I have a hieratical category structure using Taxonomies, with a custom post displayed within them. Currently the higher level categories display all the posts that are in their child categories. How do I make it only list from the current category only and not their children. I'm currently using the default code. <?php if (have_posts()) : while (have_posts()) : the_post(); ?> I'm not a programmer and have not been ably to find anything with an exact or close enough match for me to work it out.
Did you try WP_Query? Using my knowledge and the WP_Query documentation, I did this: $args = array( 'post_type' => 'my_post_type', //change the post type here 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'my_category', //change the taxonomy name here 'field' => 'id', 'include_children' => false, 'terms' => 10 //change the term id here ) ) ); $_query = new WP_Query($args); if ($_query->have_posts()): while ($_query->have_posts()): $_query->the_post(); //do something here the_title() etc endwhile; endif; wp_reset_query(); The magic should come from the `include_children` attribute. Test it out :) Is this what you wanted?
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "custom post types, custom taxonomy, custom post type archives" }
Wordpress performance - send all metaboxes to function or to call it again I need to send my metabox information to a function - the meta is already called on page template `$meta = get_post_meta(get_the_ID())` but I need to use this data in function the metaboxes are around 20 and containing different information (strings, arrays, multidimensional arrays, etc) **For best WordPress performance which is better option** \- to send all the meta to function (case 1) or to send just the ID of the post and inside the function to call the meta again (Case 2), or it is equals? _Case 1_ `somefunction($meta);` _Case 2_ //page.php somefunction(get_theID()); //functions.php somefunction($id){ $meta = get_post_meta($id); //rest of the code handling the meta }
Meta retrieval go through Cache API, so retrieving same data for same post during same page load won't cause database re–querying (and in case of Object Cache even between different page loads). So that concern aside I would recommend (as usual) to: 1. Architect in a way that makes sense, not in a way that might or might not be faster (guessing isn't worth it) 2. Benchmark the result
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, performance" }
Do I have to widgetize my pages? I have a three pages. On front page I want to show some custom test about page1,link to page1, custom text about page2, link to page2, custom text about page3, link to page3. And then I want a another page that includes texts from all three pages on one page-template. Is the correct way then to make widgets of these three pages?
Use page templates and template parts. On your _Front Page_ , you include the Texts as Template Parts: Front Page +---------------+---------------+---------------+ | Page A | Page B | Page C | +---------------+---------------+---------------+ | Link Page 1 | Link Page 2 | Link Page 3 | | Text 1 (TP1*) | Text 2 (TP2*) | Text 3 (TP3*) | +---------------+---------------+---------------+ Then you reuse them in your other (page) template: Other Page +-----------------+-----------------+-----------------+ | Content | +-----------------+-----------------+-----------------+ | Template Part 1 | Template Part 2 | Template Part 3 | +-----------------+-----------------+-----------------+ That's maybe easier than creating widget areas and fetching _static text_ from the DB.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, widgets" }
Moving away from MD5: Where to declare the custom global $wp_hasher? I want to move away from using MD5 for hashing passwords in the database. The plan is to declare a custom global `$wp_hasher` as hinted at in the docs for `wp hash password()`: > Unless the global $wp_hasher is set, the default implementation uses PasswordHash, which adds salt to the password and hashes it with 8 passes of MD5. I want to declare `$wp_hasher` like this (Blowfish or extended DES, 16 rounds of hashing): global $wp_hasher; $wp_hasher = new PasswordHash(16, FALSE); Where do I put this code so that the custom `$wp_hasher` is declared by the time it's referenced in `wp_hash_password()`?
What I would do is this: Since `wp_hash_password()` is a "pluggable" function, create a simple plugin or MU-Plugin and define a function called `wp_hash_password()` in that plugin/mu-plugin. Wordpress will use your function instead of the core function. Just copy the original code into your plugin/mu-plugin and change the one relevant line.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "security, password, encryption" }
Function to get URL of original uploaded image - full size I am currently using the following code to get the URL of the featured image of a wordpress post: URL="<?php if (function_exists('wp_get_attachment_thumb_url')) {echo wp_get_attachment_thumb_url(get_post_thumbnail_id($post->ID), 'big-size'); }?>" But the code only returns the smaller (150x150px) thumbnail. This is what I get: My question is, how do I get it to return the URL for the original image (full sized image) which would be: Many thanks for your time and help.
There are four valid sizes built in to the WordPress core. the_post_thumbnail('thumbnail'); // Thumbnail (default 150px x 150px max) the_post_thumbnail('medium'); // Medium resolution (default 300px x 300px max) the_post_thumbnail('medium_large'); // Medium Large resolution (default 768px x 0(means automatic height by ratio) max) since WP version 4.4 the_post_thumbnail('large'); // Large resolution (default 640px x 640px max) the_post_thumbnail('full'); // Original image resolution (unmodified) The last is one you're looking for. The following returns the URL. <?php $src = wp_get_attachment_image_src( $attachment_id, $size, $icon ); echo $src[0]; The whole code can look like that: <?php $src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full', false ); echo $src[0]; // the url of featured image More information can be found here.
stackexchange-wordpress
{ "answer_score": 40, "question_score": 15, "tags": "images, urls" }
Creating multisite in wordpress using php I am trying to create multisite in wordpress, I am using `WPMU DEV` and adding new sites through `My Sites -> Network Admin -> Sites -> Add New`, is there any way I could write a php code to automate this part and add site dynamicall instead of adding them dynamically. I hope my question is not too confusing, I would appreciate any help. Thanks
There is a PHP function to create sites: `wpmu_create_blog()`. The simplest example is: <?php $domain = "something.example.com"; $path = "/"; $title = "Look at my awesome site"; wpmu_create_blog($domain, $path, $title); The catch here is you need to have WordPress loaded too in your PHP. If you are doing this as part of a plugin, then you'll have no problem. But if you are doing this from an outside script, then you'll need to manually load WordPress PHP code. <?php # Load WordPress barebones define( 'WP_USE_THEMES', false ); require( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' ); $domain = "something.example.com"; $path = "/"; $title = "Look at my awesome site"; wpmu_create_blog($domain, $path, $title); I've omitted an security checking here which I leave to you.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "multisite" }
How to change “Dashboard” text in wordpress !enter image description here I need to change "Dashboard" text in wordpress admin section. Any idea how I can accomplish this?
If you put the code below on your functions you should be able to filter the `global $title` easily on the `admin_head` action. <?php add_action( 'admin_head', 'q167372_dash_name' ); function q167372_dash_name( ){ if ( $GLOBALS['pagenow'] != 'index.php' ){ return; } $GLOBALS['title'] = __( 'Your new Title' ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "customization" }
Properly licensing a plugin that uses Apache 2.0 licensed code Am developing a plugin that I would like to submit to the WordPress.org repo. It's dependent on Apache License 2.0 code, so I know I should license my plugin with GPLv3 - it's allowed. So, how do I properly license my plugin? Obviously I should include _License: GPLv3_ in my plugin's header, but it feels like there's more I should do. What else should I do?
From WordPress point of view — not much, beyond plugin's header (and even there) it is hardly policed. From licensing point of view you obviously need to accommodate requirements of both licenses accordingly. At least — make clear that your combined work is under GPLv3 and which parts of it are based on Apache License 2.0 code. GPL site has instructions on how to apply terms, although recommendation to have it done in _every_ source file is widely disregarded in practice.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "plugin development, licensing, plugin repository" }
the_content() seems to block my ACF-code I have this simple code, but can't get the_content and the ACF-code to work together. If I include the_content() it blocks out the ACF-code, but if I remove the_content() the ACF-code works fine. I suspect there's a very simple solution to this. I've simplified and removed unnecessary elements from the code below: <?php while ( have_posts() ) : the_post(); ?> <?php the_content(); ?> <?php if( have_rows('boxes') ): ?> <p>This is only shown when the_content() is removed.</p> <?php else : // no rows found endif; ?> <?php endwhile; ?>
Just for information, this is a bug in WP and autop. You can view the ticket here and it does not look like it will be fixed any time soon. The work around is to start your multiline comment with `<!--` and end it with `<!-- -->`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "loop, advanced custom fields, the content" }
Category page with posts from 2 different childcategories I have a category and will query posts from 2 different child categories see below. This is my structure 1 category - 1.1 category <- her we are (on this category i will show the posts from 1.1.1 and 1.1.2) -- 1.1.1 category <- In this category are the posts -- 1.1.2 category <- And this category are the posts 2 category - 2.1 category -- 2.1.1 category -- 2.1.2 category Thx for help.
To include posts from one or more specific categories, you can use and define category__in parameter in your WordPress query. Like this, here is an example. $args = array( 'category__in' => array( 11, 15 ), ); $my_query = new WP_Query( $args ); if ( $my_query->have_posts() ) : while ( $my_query->have_posts() ) : $my_query->the_post(); get_template_part( 'content', get_post_format() ); endwhile; endif; wp_reset_postdata(); Where `11, 15` are the category ids of the categories that you want to include posts from. You can add as many categories as you want. You just have to add comma separated ids of those categories.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development" }
How to hook into the CPT's title placeholder? I want to change the default **placeholder text** in my Custom Post Type title field. This isn't possible while registering a new post type. The following screenshot describes it. !Screen from WP Admin
I use a code which differs from yours a little bit. There is no need to get the current screen using the `enter_title_here`-filter because you have already a post-object: /** * Filter: Modifies the standard placeholder text * @param string $title * @param WP_Post $post * @return string */ function my_enter_title_here( $title, $post ) { if ( 'POST_TYPE' == $post->post_type ) { $title = 'Custom placeholder text here'; } return $title; } add_filter( 'enter_title_here', 'my_enter_title_here', 10, 2 );
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "custom post types, hooks, title" }
Backbone.js and WP API I'm creating a theme based on the underscore theme with Backbone.js integration. I am struggling to find any clear examples/documentation on the WP-API plugin's capabilities, and starting to find it fairly frustrating. I am pulling in a basic list of posts using the following code: var posts = new wp.api.collections.Posts(), posts.fetch(options).done(function(){ console.log( 'we now have 10 posts'); } This works fine. The problem is I wish to retrieve some post_meta at the same time, without making multiple fetch calls asynchronously (one per post). There are some post_meta fields I wish to use, as well as getting the post thumbnail. Any direction is appreciated.
Inside the PHP side of things, there is a `json_prepare_post` filter, which allows you to alter the loose `Post` object returned. Here you can attach meta data and other things, such as post thumbnails. add_filter( 'json_prepare_post', 'eh_json_prepare_post' ); function eh_json_prepare_post( $_post ) { $_post['post_meta']['some-value'] = get_post_meta( $_post['ID'], 'some-value', true ); return $_post; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "backbone, wp api" }
WP Admin default view mode for Custom Post Type To change it globally to `excerpt` for every post type I can use: function my_default_posts_list_mode( $default ) { return 'excerpt'; } add_filter( 'default-posts-list-mode', 'my_default_posts_list_mode' ); But how can I achieve the same only for a Custom Post Type? **Explanation:** I've created a Custom Post Type. In WP Admin the default view mode is set to list (edit.php?post_type=my_post_type&mode=list). I want it to be `excerpt`, but **only** for my Custom Post Type not affecting other post types. I can do this manually by adding `&mode=excerpt` to the URL like so: `edit.php?post_type=my_post_type&mode=excerpt`, however I want this to be done automatically.
To change the mode URL variable but in the load try this: add_action( 'load-edit.php', 'my_default_posts_list_mode' ); function my_default_posts_list_mode() { $post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : ''; if ( $post_type && $post_type == 'my_post_type' && !isset( $_REQUEST['mode'] ) ) $_REQUEST['mode'] = 'excerpt'; } Got the "insipration" from here: Set Default Listing "View" in Admin
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "custom post types, filters, wp admin, views" }
How to copy data from user profile page (profile.php) to theme customizer i am trying to figure out how to copy data from user profile page (profile.php) to theme customizer. i want to copy some data from some fields, when theme is activated. and stored the data in theme customizer, so when the user will enter to theme customizer he will see all data there. i using gravity forms as register form with some custom fields. the same fields i have created in the user profile page (profile.php). so when user register, this data stored in user profile page. like **address, phone and etc...**
anybody that looking for solution here is what i found that work for me. to get some data from any field in profile page you need to use this function: <?php get_the_author_meta( $field, $userID ); ?> then if you want to update some value in theme customizer you can use this function: set_theme_mod( 'field name', '$value' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, theme development, profiles, theme customizer" }
Retrieve featured image as object I want to retrieve the featured image of a post as an object (`array`) in order to have all image sizes available. The `get_the_post_thumbnail()` function doesn't do this, any ideas?
First get the registered image sizes and the featured image attachment id: $sizes = get_intermediate_image_sizes(); $post_thumbnail_id = get_post_thumbnail_id(); Loop through the registered sizes and create an array: $images = array(); foreach ( $sizes as $size ) { $images[] = wp_get_attachment_image_src( $post_thumbnail_id, $size ); } Combined as a function to place inside functions.php: function get_all_image_sizes($attachment_id = 0) { $sizes = get_intermediate_image_sizes(); if(!$attachment_id) $attachment_id = get_post_thumbnail_id(); $images = array(); foreach ( $sizes as $size ) { $images[] = wp_get_attachment_image_src( $attachment_id, $size ); } return $images; } Usage: $featured_image_sizes = get_all_image_sizes();
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "post thumbnails" }
Increasing post view count automatically I am testing a ranking system for posts, and I'd like help with the below: Upon publishing a new post, I'd like the post view count to immediately have a random number between 829 and 1013 added to it. Could you please tell me how I can do that? If you offer any code, kindly let me know exactly where to put it. Thank you.
You can automatically add a custom field to each new post on publish (on change status to publish). And then set it's value to a random number between 829 and 1013. Here is the function that will do just that. // Create custom field on post publish function wpse_custom_field_on_publish( $new, $old, $post ) { if ( $new == 'publish' && $old != 'publish' && !get_post_meta( $post->ID, 'post_views', true ) ) { add_post_meta( $post->ID, 'post_views', rand(829, 1013), true ); } } add_action( 'transition_post_status', 'wpse_custom_field_on_publish', 10, 3 ); In above code, `post_views` is the name of the custom field that we are using to count post views. You should change it to yours before using it in your theme. Just FYI, this will go in `functions.php` file.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "count, views" }
Adding class to featured image I have specified a loop to show featured images for my custom post type and wish to add a img-responsive class from bootstrap to my featured image. How can I do this? Thanks! Code: <div class="home-featured-img"> <?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it. the_post_thumbnail(); // show featured image } ?> </div>
You can add custom class to post thumbnails. the_post_thumbnail accepts array of attribute `$attr` where you can specify image class. So your code will be. <div class="home-featured-img"> <?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it. the_post_thumbnail( 'full', array( 'class' => 'responsive-class' ) ); // show featured image } ?> </div> In above code, `responsive-class` is the custom class I have added, you can change it as you require.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "custom post types, images, twitter bootstrap, post class" }
Nginx url rewrite rule problem I am facing a problem with the permalink. Urls like ` works fine with the help of `try_files $uri $uri/ /index.php?q=$uri&$args;` Right now i am working on temporary link which is like ` Now the link ` doesn't work and gives **500 Internal Server Error** Note: I am using `webuzo` as my server control panel.
It looks like your'e missing the subdirectory part relative to the `root` setting, try this instead: try_files $uri $uri/ /wordpress/index.php?$args; and you shouldn't need the `q=$uri` part. For subdirectories `dir1` and `dir2`, you could wrap the `try_files` with `locate` blocks, something like: location /dir1/ { try_files $uri $uri/ /dir1/index.php?$args; #... } location /dir2/ { try_files $uri $uri/ /dir2/index.php?$args; #... }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "permalinks, nginx" }
Add CSS Class to Link in TinyMCE editor In searching for a solution, I've come across the plugin to enable a dropdown of CSS styles already present within a stylesheet. What I want is to allow the editor to add CSS Classes from a textbox. So if you consider this image: !enter image description here What I'm ideally looking for is a way to get another textbox in there below **Title** called _Class_. The freedom to type in a CSS class is needed for other functionality within the site. Any ideas on how I can achieve this? Many thanks!
I was able to solve this by adding the WP Edit plugin to my site. It has an _Advanced Link_ button, that allows me (or an editor) to manually type in a classname.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 9, "tags": "links, tinymce" }
How to speed up installing plugins and upgrading WordPress I currently run on a VPS that is running the latest version of Ubuntu, PHP 5.5.9, and WP 4.0, and have been running my plugin upgrades through `libssh2` via a configuration in `wp-config.php` ever since I started working on this VPS, as WordPress is unable to open a connection automatically. However, within the past week or so, I've noticed plugin installs and WordPress upgrades have become increasingly slow, with the browser hanging for almost 1-2 minutes before confirming that my plugin is installed. (Jetpack takes an extremely long time to update, as an example.) One side effect that I've noticed is that PHP often exits before the `.maintenance` file is removed. Problematic, as I then have to go and remove it myself by connecting to the server. Is there a way I can speed things up and get PHP to run faster?
As you're using a VPS with SSH access, give WP-CLI a try < can work wonderfully < for example to install limit login attempts plugin just run this command from SSH within your wordpress install directory wp plugin install limit-login-attempts --activate --allow-root full list of command line options at < updating plugins < & < wp plugin update limit-login-attempts --allow-root
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, updates" }
Is there an action like 'after_register_custom_post_type'? I'm writing a small plugin for Visual Composer. I need to list all custom post types but I don't know when to call the query to fetch all post types. My plugin gets initialized by `after_setup_theme`, but the function which queries the custom post types don't list custom post types, because its executed too early. The problem: custom post types can be created within theme files (e.g. `function.php`) or plugins (like `Custom Post Type UI`). Which action should I use to get all custom post types? I know that Advanced Custom Fields does the same (you can create custom fields for every (custom) post type), but I can't find the piece of code that does the trick.
Just as @PieterGoosen mentioned, in a deleted comment, the post types should be registered within a `init` hook callback. The `after_setup_theme` action is fired before `init`, so that hook will not help you. Try for example hooks fired after `init`, like `wp_loaded`. Here's for example a list of the actions order from my vanilla install.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugin development" }
Disable site visiting and user logins excepting for a specific user I want to disable temporarily site visiting and user logins to a multisite blog for the site maintenance time, excepting for super-admins and for a specific user. I found this function (thanks @joshc) and it works very well, but I don't know how to add the specific username to it so it can visit the site too. Please help! This is what I tried, but without success, the user _test_user_ is not allowed to login: function site_maintenance() { global $user_login; get_currentuserinfo(); if ( !is_super_admin() || $user_login != 'test_user' ) { $logout_url = wp_login_url().'?mode=maintainance'; wp_logout(); wp_redirect( $logout_url, 302 ); die(); } } add_action('get_header', 'site_maintenance');
Your `if` case matches any user who is not both a super admin and `test_user`. For example, given a user `test_user` who is not superadmin, the result would be if (true || false) redirect Since one condition is true, the redirect would be triggered. Using the `&&` operator, you'd get if (true && false) redirect. Since both are not true, it doesn't trigger the redirect.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, login, user access" }
preg_replace() No ending delimiter '.' found I get this error: `Warning: preg_replace() [function.preg-replace]: No ending delimiter '.' found in` but I can't figure out why Here is the code: foreach( $content as $item ) { $item = preg_replace( array('.',' '), array('-','-'), strtolower($item)); $replace = '<h4 id="'.utf8_decode($item).'">'; $phrase = preg_replace('/'.$tag.'/', $replace, $phrase, 1); } Please also tell my WHY it doesn't work
< `preg_replace` expects your first parameter to be a pattern. Try a simple replace: $item = str_replace( array('.',' '), array('-','-'), strtolower($item));
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, php" }
get_the_content within foreach not the loop I want to retrieve the content of posts within a foreach loop. $recent_posts = wp_get_recent_posts(); $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); $content = apply_filters( 'the_content', get_the_content() ); $content = str_replace( ']]>', ']]&gt;', $content ); foreach( $recent_posts as $recent ){ echo '<img src="'. $url .'">'. '<a href="'. get_permalink($recent["ID"]) .'"><h1>'. $recent["post_title"] .'</h1><h2>'. get_the_date() .'</h2><p>'. $content .'</p></a>'; } but it gives me an empty `<p>`. Is it not possible to use `get_the_content();` like this? Thanks
`get_the_content();` must be used in the loop for it to work as specified in the Codex. To get post content in your case you have to use `$recent["post_content"]` instead.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "content, php" }
How to list all active and specific shortcodes in wordpress I wonder how you can list specific shortcodes, for example with this code you get a list of all active shortcode tags: <?php global $shortcode_tags; echo '<pre>'; print_r($shortcode_tags); echo '</pre>'; ?> I want to create a statement to get specific shortcodes tags for example: we want a list of all shortcodes [hello] if ($shortcode_tags==[hello]) { echo '<pre>'; print_r($shortcode_tags[hello]); echo '</pre>'; } Any suggest; thank you
The conditional needs to test against strings which would be the name of the shortcode. If you're looking for the `[hello]` shortcode the conditional would look like: echo '<pre>'; print_r( $shortcode_tags['hello'] ); echo '</pre>'; So if you use `add_shortcode()` the string you'll be looking for is the first parameter: `$tag`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, shortcode" }
Price comparison table based on Custom Post Type? I have created a review site where clients can rate their hosting providers based on various factors, however since the launch, many have asked if it would be possible to create a price comparison table so they could look for provider's in their price range. I believe the best way to do this will be to create a Custom Post Type and have fields for the 5-10 most common packages, where I can create a new CPT entry for each provider and set the prices there (or even give the providers access to do so themselves). Would this be the best way to go about this with Wordpress? How can I create a page that loops through each entry for that CPT and pulls the information I need to build this table?
I suggest just making a new Post Type with the default Wordpress register_post_type(). function create_my_post_type() { $labels = array( 'name' => __( 'Providers pricing', 'myplugin_namespace' ), 'singular_name' => __( 'Provider pricing', 'myplugin_namespace' ), 'menu_name' => __( 'Provider Pricing', 'myplugin_namespace' ), ); $args = array( 'labels' => $labels, 'public' => true, 'description' => __( 'Pricing stuff for my awesome plugin', 'myplugin_namespace' ), 'show_in_menu' => true, 'supports' => array( 'title', 'thumbnail' ), // or whatever else you want from WP_Post 'has_archive' => true, ); } To be clear: this should be run during plugin initiation. To add custom meta-boxes for your fields, read up on the function `add_meta_box()`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, custom post types, custom field, loop, pages" }
How can I show <li> only if custom field has content I have the following code: <font size="2">Pistas:</font></p> <ul> <li> <?php echo types_render_field("pista-1a", array("argument1"=>"value1","argument2"=>"value2","argument2"=>"value2")); ?><li> <?php echo types_render_field("pista-1b", array("argument1"=>"value1","argument2"=>"value2","argument2"=>"value2")); ?> </li></ul> ' As you can see... I manually inserted * in every item, but sometimes not all fields have contents, so in this case, the * bullets show with no content in front of them.. how can I change the code to insert * only if the custom field is not empty.... (I'm using Types Plugin) Sorry for my basic coding, I'm not a programmer and I'm learning a little as I try to adapt my theme to my needs Thanks a lot folks!
Again, I'm not familiar with Advanced Custom Fields but you may be able to store the returned value into a variable then test if that variable is empty, like so: <?php $pista1a = types_render_field("pista-1a", array("argument1"=>"value1","argument2"=>"value2","argument2"=>"value2")); ?> <ul> <?php if( ! empty( $pista1a ) ) : ?> <li> <?php echo $pista1a; ?> </li> <?php endif; ?> </ul>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, customization, plugin types" }
Disable only the comment form/box itself? I'm trying to write a function which hides the comment form itself, while leaving comments and comment counts intact. I'd like the comment form to display only when a certain parameter is in a post URL. All I can find is code which disables everything comment related. And I came up with a method which would require some css (give form another ID when it needs to be hidden and then display: none;). Does anyone happen to know of a PHP-only method?
The `comments_open()` function is used, both by core and typically themes to determine status for specific post. It has filter of same name for result, which you can use to manipulate it individually for the post. `comment_form()` won't actually output form if check is false and fire `comment_form_comments_closed` action in such case. Native WP themes, shipped with core, are also good examples of building this check into templates.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments, forms" }