INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Unexpected Output: register_activation_hook with namespace I encounter a weird error while using the `register_activation_hook` and `namespace`. > The plugin generated 236 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin. I get this error even with this simple plugin: <?php /** * Plugin Name: Sample Plugin * */ namespace Sample; register_activation_hook( __FILE__, 'sp_activate' ); function sp_activate() { } If I remove the `namespace` the error does not occur. Do I miss something? What is wrong here?
When we are outside the `Sample` namespace, we should call the function by `\Sample\sp_activate()`, so please try the following: <?php /** * Plugin Name: Sample Plugin * Version: 0.0.2 */ namespace Sample; \register_activation_hook( __FILE__, '\Sample\sp_activate' ); function sp_activate() { } If something is printed out during the plugin activation it will result in unexpected output message. If you use for example `echo 'Hello';` in your activation function, it will generate such a message of 5 characters. You should consider using `WP_DEBUG_LOG` and log the errors into a file, to see what kind of errors you're getting there. I hope this helps.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "errors, activation" }
404 Admin Error I am new to WordPress and was looking at settings in the admin. I believe I changed the directory of the site from `example.com/wp/` to `example.com`. When I saved the changes I immediately saw a 404 error that says: Not Found The requested URL /index.php was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. In trying to fix what I messed up I came across this question which an answer said to `Delete .htaccess` however I believe the root cause in that question is different than my problem.
I found the solution. I had to open up `phpMyAdmin` open up the database then open up `wp_options`. From there I had to change the `siteurl` and add `/wp` to the end and it works again.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin, 404 error" }
How to extract translatable (double underscores and _e) strings? I made a custom theme and wonder how could I extract all translatable strings to a .po file so I can translate it. Do I need WPML plugin? Ex: I have a string "soccer" which is written as `_e('soccer','mytheme');` and I want to translate it to "futebol" but how can I transport it to a .po file?
One way is to use the WordPress i18n tools. I had to checkout WordPress trunk to make it work. On the command line: svn co once you have trunk somewhere, you'll then want to call the `makepot` script. Again, on the command line: php /path/to/wordpress/trunk/tools/i18n/makepot.php wp-theme /path/to/your/theme/ After that script has run, the pot files will be in whatever directory was specified in the above `/path/to/your/theme` More information and a couple of other methods can be seen here: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "translation" }
Add Incrementing ID to each paragraph in the_content I need to loop through each paragraph in the_content and add an ID to each paragraph with an incremental value. function incrementparagraphs( $content ) { for ($i = 0; $i <count($content); $i++) { return str_replace( "<p>", "<p data-section-id=" . $i . ">", $content ); } } add_filter( 'the_content', 'incrementparagraphs', 10, 1 );
If I understand your question correctly, you can try the following: add_filter( 'the_content', 'incrementparagraphs', 10, 1 ); function incrementparagraphs( $content ) { return preg_replace_callback( '|<p>|', function ( $matches ) { static $i = 0; return sprintf( '<p data-section-id="%d">', $i++ ); }, $content ); } to replace every `<p>` tags with `<p data-section-id="1">`, where the `data-section-id` attribute contains the incremental count of the current `p` tag. ## Example: **Before:** <p>aaa</p> <p>bbb</p> <p>ccc</p> **After:** <p data-section-id="0">aaa</p> <p data-section-id="1">bbb</p> <p data-section-id="2">ccc</p> More on `preg_replace_callback` here.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "loop, the content, php" }
Display admin notice only on main dashboard page I'm using following code to display a notification in the admin dashboard. I want to display only on the main dashboard page (index.php), however the following code would display on all pages in the dashboard. Is there anyway to restrict it only to the dashboard main page? Thanks. function my_admin_notice() { ?> <div class="updated"> <p><?php _e( 'some message', 'my-text-domain' ); ?></p> </div> <?php } add_action( 'admin_notices', 'my_admin_notice' );
You can try the following: function my_admin_notice() { ?> <div class="updated"> <p><?php _e( 'some message', 'my-text-domain' ); ?></p> </div> <?php } add_action( 'load-index.php', function(){ add_action( 'admin_notices', 'my_admin_notice' ); } ); where we use the `load-index.php` hook to target the _dashboard_ page.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "theme development, dashboard" }
Functions.php in child theme that loads CSS file breaks website I created a child theme and created a functions.php file in the child theme directory that also has the required style.css file and a seperate custom CSS file that I want to load. This is the code I use: <? php add_action('wp_head', 'add_landing_css'); function add_landing_css() { wp_enqueue_style('landing_css', get_stylesheet_directory_uri().'/landing.css','screen'); } ?> When I add this code to functions.php every page on my website is blank. It doesn't load anything. When I delete functions.php file my website works as normal. I use a theme called Modest from elegant themes.
The reason for the syntax error is this typo: <? php It should be <?php Secondly, you should use the `wp_enqueue_scripts` hook instead of the `wp_head` hook. Check out the Codex for more info on the `wp_enqueue_scripts` hook.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, css, child theme" }
Line break no working on theme I am working on an e-commerce site and the line breaks wont work, neither using the return button nor using `<br />` . I have been looking around but haven't found a solution that works. I would need to let the user simply push the return button and have a line break as he won't be experienced. Any help would be much appreciated, thanks in advance.
It is possible to add line breaks using `&nbsp;` in the "Text" view like so: < One thing to be aware of is that once you add the HTML for non-breaking spaces, you must remain in the "Text" view for future edits; switching back and forth to the visual editor will remove the above code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, editor, line breaks" }
Switch site language to en_ZA I've translated my site to English/South Africa - there's different translation for regular English - but I cannot figure out how to switch the site to `en_ZA`. I have multisite install, and the domain I need to switch the language for is domain.com/za. How to do this, any suggestions?
You need to set a locale filter, please see: < for an example, Enjoy,
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "multi language, language" }
Strip shortcode from specific post types (formats) I am trying to remove the shortcode from a specific post type, in this case link. I used this code on my functions.php but it removes the shortcode from the_content for every post type. <?php function remove_shortcodes( $content ) { return strip_shortcodes( $content ); } add_filter( 'the_content', 'remove_shortcodes' ); is it possible to modify this so it only remove the shortcode from "Link" post type? thanks
You would need to use WordPress Conditional Tags to query if this page is the custom post type you are wanting to target and then if it is remove shortcode. Untested but you can try this: function remove_shortcodes( $content ) { if ( get_post_type() == 'post-type-name' ) { return strip_shortcodes( $content ); } else return $content; } add_filter( 'the_content', 'remove_shortcodes' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "custom post types, shortcode, post formats" }
Different back-end colour scheme for the different sites of a multisite Is it possible to have a different back-end colour scheme selected for the different sites of a multisite? i.e. "Sunrise" for Site A and "Midnight" for Site B If it's not possible for the user to setup could it be enforced through a plugin or the theme?
Add to your functions.php file the following code, this will hook into your admin header section and will place the style you chose accordingly to the matching site. add_action('admin_enqueue_scripts', 'my_admin_background'); function my_admin_background() { wp_enqueue_style( 'custom-style', get_template_directory_uri() . '/css/custom_script.css' ); global $blog_id; $color = ''; if ($blog_id == 1) { $color = 'white'; } elseif ($blog_id == 2) { $color = 'red'; } elseif ($blog_id == 3) { $color = 'blue'; } else { $color = 'yellow'; } $custom_css = "<style> body { background: $color } </style>"; wp_add_inline_style( 'custom-style', $custom_css ); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 5, "tags": "multisite, users" }
Is it possible to get feature image url (full-size) from an image url of smaller size? Supposing that we know nothing except the url of image (smaller size e.g. 150x150) What is the best way to get its full-size image url from the url above? or Just easily remove the prefix "-150x150" ? (I'm not sure if this is proper since i need best practice also.)
The URL for rezied images in WordPress is constructed in a way that's impossible to direct reverse. Therefore, it's impossible to get the attachment associated with a URL of a resized image with 100% certainty, unless you loop through all attachments and check whether their URL matches the given URL. However, this approach is very slow and resource-intensive. In any normal WordPress setup, you can rest assured that, given a URL of a resized image, you can retrieve the full image URL by removing the dimensions from the URL. This is, however strange it may seem, best practice.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images" }
How to check if there is image title, caption, description? I use this code to display featured image title, caption (excerpt), description (content): `echo get_post(get_post_thumbnail_id())->post_title; echo get_post(get_post_thumbnail_id())->post_excerpt; echo get_post(get_post_thumbnail_id())->post_content;` But, how to check if there is any of those fields first? For example, how to check if there is caption, and if emty to show some other text? Best regards.
It's more a programming question, but try this: $post = get_post( get_post_thumbnail_id() ); if ( !isset( $post->post_title ) ) { echo 'Sorry no title'; } else { echo $post->post_title; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "attachments, images, captions, featured post" }
Wordpress is trimming leading 0s I am inserting into the DB in the following manner: // insert the info into the db $wpdb->insert( 'wp_vkrwps_table', array( 'zip' => $zip ), array( '%d' ) ); // end insert However, leading zeros keep getting trimmed. So if the input value is for example `00501`, I end up getting `501` in the DB table. Why is this?
`%d` means integer, integers don't have leading zeros. Zip codes aren't numbers in the sense that they quantify something, they're strings that happen to be made up of numbers, so treat them as strings.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "wpdb" }
How to show file type of featured image? How to show file type of featured image in post on single.php? For example: Featured image type is: ".jpg" I can get mime-type, like "image/jpeg". It could be also some check of image mime-type first, for example if image mime-type is "image/jpeg" then echo ".jpg" if it is "image/gif" echo ".gif".
If you want to show the File type of featured image. then try the below code. <?php $id1 = get_post_thumbnail_id($post->ID); $type = get_post_mime_type( $id1 ); $mime_type = explode('/', $type); $type = '.'.$mime_type['1']; echo $type; ?> It will display the exact extension that you want ".jpeg" from "image/jpeg" Here "$post->ID" is current post id (or the id of the post whose featured image you want ). Check if it works for you.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -3, "tags": "images, featured post" }
Orientation of featured image in post? Is it possible to show orientation of featured image in post on single.php? For example: Orientation of featured image is: portrait / landscape. * * * I have found that this could be done by calculating aspect ratio of image (width / height). For example image with dimensions 1600 x 1200 have aspect ratio 1.33333 (landscape) and 1200 x 1600 have aspect ratio 0.75 (portrait). If you are interested to find more look on: Get total number of pixels, size in megapixels and aspect ratio based on image width and height?
Basic check of aspect ratio. Display as landscape, square or portrait if ( !has_post_thumbnail()) { return 'Error'; } else { $image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), ''); $image_w = $image[1]; $image_h = $image[2]; if ($image_w > $image_h) { echo 'landscape'; } elseif ($image_w == $image_h) { echo 'square'; } else { echo 'portrait'; } }
stackexchange-wordpress
{ "answer_score": 4, "question_score": -2, "tags": "images, featured post" }
How to add multiple images to a custom post type single post? I have created a custom post type and I need to add multiple images to every single post, so I can create a loop and use them in a slider. So far my search on Google etc. has turned up nothing. What's the cleanest way to add a metabox to the custom post type, so I can add images to the post and create a loop to display them in a slider/gallery?
Thanks for the suggestions, guys. I did some more research, and found this - < It's a great plugin that lets you attach images to the post without inserting them in the post and the images can be easily sorted with ajax, it's also quite modifiable and just what I needed, and works on custom post types. You just create a loop and you can use the images in any slider.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "custom post types, wp query, theme development, metabox" }
PHPStorm variable warnings I code in PHPStorm and include wp-admin and wp-include in my path, but get code inspection warnings related to undefined / unused variables. Should I be concerned about these? How would I go about satisfying a resolution to resolve the error (without just turning inspection off) !enter image description here
This happens because you are using `extract()`, and PHPStorm cannot know where the variable is coming from. Do not use `extract()`. Ever. It was removed from almost all WordPress functions, and so should you do.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "ide" }
Get List of all the Authors How could i get List of all the Authors? author.php file shows the Information about Individual Author. for example: < that returns the Bj's Profile. if i enter < it returns **404 Not Found** Author page shows author's avatar, Author's Name and description. how can i list out all the authors? Need Help!
You can display author's list by using function `wp_list_authors` for more info : < And for author Template Hierarchy see below link <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query, loop, author, list authors" }
Keeping social share count after changing Wordpress Permalinks I am going to change wordpress permalinks and will do 301 redirect from old to new URL's. But the problem is how can i keep my social sharing counts (like facebook,twitter, google +1) after the URL's are changed. Thanks
You would have to put the old link into the url attribute for each of the share buttons. For example: <a href=" class="twitter-share-button" data-url=" data-via="your_screen_name" data-lang="en">Tweet</a> Twitter also has an attribute called `counturl` which might be worth looking at. You'll have to do a bit of research on the others.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "social sharing" }
Call another page in forms I am doing some practice for WordPress plugin. In plugin I am working on a form and what I need is to call another page on submission. I have tried that but nothing seems to work. <form method = "Post" action = "some_file.php"> </form>
Wordpress has a generic handler to deal with all forms - admin-post.php. If you include a hidden field in your form called action, you can then hook in to a function of your choice with all the goodness of wordpress included. echo "<form action='".get_admin_url()."admin-post.php' method='post'>"; echo "<input type='hidden' name='action' value='submit-form' />"; echo "<input type='hidden' name='hide' value='$ques' />"; { Enter the rest of your first block of code from above here } And then in your functions.php file (or any other php file that you have included via functions.php), you can use this method. add_action('admin_post_submit-form', '_handle_form_action'); // If the user is logged in add_action('admin_post_nopriv_submit-form', '_handle_form_action'); // If the user in not logged in function _handle_form_action(){ { Enter your second block of code from above here } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, forms, template redirect" }
How to know which archive page is active I have two custom post type name as 'product' and 'blog'. And I have also two archive page 'archive-product.php' and 'archive-blog.php'. Now, I want to know which archive page is active. Example: We know `is_page('contact')` if page is contact then it return true. But what about archive pages. I've used `is_archive('blog')`, but this function always returns true on both product archive or blog archive active. So is there any way to know is this archive page 'product' or 'blog' is active
First of all, `is_archive()` does not accept any parameters if you have read the codex, that is why it will always return true no matter what you tried on any archive page As pointed out `is_post_type_archive( $post_types )` is the proper conditional tag to use to check for a specific post type archive page. One thing though, your question is unclear on how you would like to use this condition, as you already have an archive page specially made for each custom post type, so to check if your on a specific archive page would not make sense. `is_post_type_archive('blog')` will always return true on archive-blog.php while `is_post_type_archive('product')` will always return false, and `is_post_type_archive('product')` will always return true on archive-product.php while `is_post_type_archive('blog')` will always return false.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, archives" }
Make Post Editor Select Number of Columns To 1 By Default I want to make the Number of Columns in screen options for a custom post type is selected to 1 by default, instead of 2, which means full screen. How this can be done?
Ok, so this is how I did it. This hook into the admin head, find the screen options part and set the default checked radio button to `1`, which mean full screen. Just found the answer from here and give it a little modification: add_action( 'admin_head', 'wpse1152474_post_editor_columns'); function wpse1152474_post_editor_columns() { global $pagenow, $typenow; if ($pagenow == 'edit.php' || $pagenow == 'post.php' || $pagenow == 'post-new.php' && $typenow=='your_targeted_post_type') { add_screen_option( 'layout_columns', array( 'max' => 2, 'default' => 1 ) ); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, editor, screen options" }
save_post action hook for comments Is there a action similar to save_post for comments? Already tried comment_post which does not fire when clicking the update button on a comment in WordPress.
You can try the `edit_comment` hook that's fired within the `wp_update_comment()` function, called by the `edit_comment()` function when you edit a comment in the backend. This hook is fired after the comment is updated in the database. **Example:** add_action( 'edit_comment', function( $comment_ID ) { // ... your code here ... } ); Notice the following comment in the source: > The hook also fires immediately before comment status transition hooks are fired. I find this comment somewhat confusing, because it's actually the `get_comment` filter that's fired immediately before the comment status transition hooks are fired within the `wp_transition_comment_status()` function. But it's true if _hook = action_ , but I usually understand the meaning of the word _hooks_ to be both _actions_ and _filters_. But this was just a minor detour. ps: My first thought/guess was `save_comment`, before I checked the source ;-)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "comments" }
pre_get_posts causes Custom Posts appear under 'Pages' menu In order to enable pagination on for custom post archive I've added pre_get_posts function. But, funnily it caused my custom posts be duplicated under 'Pages' menu. Here is the code that causes the problem. Please, advise. function truck_pre_pagination( $qry ) { if ( $qry->is_main_query() ) { $qry->set('orderby','date'); $qry->set('order','ASC'); $qry->set('posts_per_page',12); $qry->set('post_type','trucks'); } } add_action('pre_get_posts','truck_pre_pagination');
`$qry->is_main_query()` will be true on every main query on your site, front end and admin. You need to add another more specific condition to target only the page you're trying to modify the query on, like `is_post_type_archive('trucks')`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy, custom field, pre get posts" }
How to get the $atts of a shortcode I have the following shortcode: [video width="400" height="400" mp4=" I need to get every single atts a single variable, I mean, I need something like this $width = 400 $height = 400 $file = does anybody have done something like this before? (I'm very newbie in WP)
Straight from the Shortcode API page on the Codex: > The raw $atts array may include any arbitrary attributes that are specified by the user. That is to say, the `$atts` parameter passed to your shortcode callback function contains all the attributes in an associative array.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "shortcode" }
P̶l̶a̶c̶e̶h̶o̶l̶d̶e̶r̶ *Default* content in Custom Post Type TinyMCE editor I know you can customize the ~~placeholder~~ _default_ text of the 'Post Title' field, but is there any way to display placeholder content in the actual TinyMCE post editor? Ideally I'd like to display several paragraphs of HTML formatted content in the editor as a placeholder / instructions.
There is no way to add "placeholder" for TinyMCE, but you can set default content for newly created posts. All you need is just to hook `default_content` filter and return your formatted paragraphs: add_filter( 'default_content', 'wpse8170_get_default_instructions', 10, 2 ); function wpse8170_get_default_instructions( $content, WP_Post $post ) { if ( $post->post_type == 'post' ) { $content = '.... your content ....'; } return $content; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, tinymce, editor" }
WooCommerce New customer email Hook? I've created a sign up page for new customers to create an account. This is working fine but I would like to hook into WooCommerce `customer_new_account` inside `WooCommerce/Classes/Emails/class-wc-emails.php` to send the welcome email. Is there an existing hook I can use or what's the best way to do this. I don't want to create another welcome email function. Thanks. **Answer** do_action('woocommerce_created_customer', $user_id, $new_customer_data, false);
There is no actions/filters to hook to. You need to override standard `WC_Email_Customer_New_Account` class and implement your own logic. To do it you need to create your own class which will inherit that class and register it. class WPSE8170_Email_Customer_New_Account extends WC_Email_Customer_New_Account { function trigger( $user_id, $user_pass = '', $password_generated = false ) { // do what you need here and then call parent method parent::trigger( $user_id, $user_pass, $password_generated ); } } Now you need to register this class: add_filter( 'woocommerce_email_classes', 'wpse8170_update_email_classes' ); function wpse8170_update_email_classes( $emails ) { $emails['WC_Email_Customer_New_Account'] = new WPSE8170_Email_Customer_New_Account(); return $emails; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "hooks, email, woocommerce offtopic" }
wp_dropdown_pages() returns empty string for post type anything other then page `wp_dropdown_pages()` while using for any post type other then `page` returns empty string. Codex says post type can be passed as key also the function uses `get_pages()` which takes the `post_type` key. So, I don't see why it isn't working for me. $args = array( 'echo' => 1, 'name' => 'my_posts', 'post_type' => 'post', 'show_option_none' => 'any' ); $select = wp_dropdown_pages($args); Any idea?
On the same codex page: > With the 'post_type' parameter you can get a drop down of any post type, including custom post types, as long as the post type in question is hierarchical. post != hierachical. That's the answer. :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post type" }
the_content() brings the medium size image So I have the problem, the image I want to dispaly in post is not big enough and in my preffered size it gets bad quality, then i noticed that is not the default size image returned it's medium size and I tried to check but didn't find anything in particular. while ( have_posts() ) : the_post(); the_content(); args = array( 'post_type' => 'attachment', 'orderby' => 'date', 'order' => 'DESC', 'post_mime_type' => 'image' ,'post_status' => null, 'post_parent' => $post->ID ); $attachments = get_posts($args); $categories = get_the_category(); endwhile;
The UI might be slightly different depending on what version of WordPess you are running but just before you select the insert button/link, simply just select 'Full Size' size image from the dropdown menu. !enter image description here
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "the content, images" }
Query to get all the posts of more than 2 meta_value having same meta_key? Meta_value will have checkbox infront of them so when both the check box is selected posts related to both the meta_value will be displayed.
From the codex < $args = array( 'post_type' => 'my_custom_post_type', 'meta_key' => 'age', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'age', 'value' => array(3, 4), 'compare' => 'IN', ) ) ); $query = new WP_Query($args); Look at the meta_query section. you can define the key and then all the possible values in a array. You can also define the type of comparison (eg. great than, equal, IN).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, metabox, meta value" }
Custom CSS for a particular text/html widget in Wordpress I have a couple of text widgets on my Home Sidebar. There is one text widget in particular that I want it to implement custom CSS written in my child theme rather than the default styling provided by the theme. Is that possible? If yes, how? Edit: the below answer generally doesn't work because most widgets have their css implemented after both, the theme style and the custom style file.
From firebug, you can see the ID name of the text widget, which is "text-some number" and this is what we need to customize. the specific WordPress widget has the class name "widget" (from class="widget widget_text".). All we need to do is add a new CSS selector to style the selected widget. #sidebar .widget #text-3564277 { background-color: #fff; border: 1px solid #ddd; padding: 10px; } or you can go for any plugins like widget css classes which will add a field to all wordpress widgets for entering the custom class. then you can style that class.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets, css, widget text" }
Get list of scripts / styles and show file which enqueued them I want to show what scripts and styles have loaded on a page and which plugin / theme / file has added them to the page. We can show all scripts and styles using: <?php global $wp_scripts, $wp_styles; var_dump( $wp_scripts ); var_dump( $wp_styles ); ?> Or more elegantly using this answer: How do I get the $handle for all enqueued scripts? I now want to be able to see where they were enqueued. For example if I had a JS file called foobar.js and it was enqueued by plugins/organge/orange.php I would want to output this file location along with the script. This is for development to help isolate what is loading what.
This is not possible the way you think. It _would maybe_ be possible if you use Reflections or `debug_backtrace()`, but there's no reliable way to do this. WordPress does not keep a stack or queue where it tracks file names. The _only_ thing I could imagine is just hooking into the action and inside `wp_enqueue_scripts()`: wp_enqueue_scripts and attach a tracking mechanism of _attached callbacks_ there. Note the `s` and that this is not the function that you use to attach scripts to the stack. <?php /** Plugin Name: (WPSE #152658) Script Loader Callback Inspector */ add_action( 'wp_enqueue_scripts', function() { var_dump( $GLOBALS['wp_filter'][ current_filter() ] ); }, PHP_INT_MAX -1 ); This would leave you with a queue of all attached callbacks. You can then trace them back with your IDE.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 6, "tags": "plugin development, wp enqueue script, wp enqueue style, debug, scripts" }
unable to display the image meta value as background I want to use meta url as background image.But the fact that I do not want to show "background-image:url('_')" this way because if my meta value is empty.What I thought to end up in this way. $bgimage= get_post_meta( $post->ID, 'settings_image', true ); < div style="<?php echo 'background-image: url(".wp_get_attachment_url( $bgimage )")';?>"> I think this is best way since I do not want to put extra conditional block here.Did I make mistake in catenation?
Very slight one, see below :) $bgimage= get_post_meta( $post->ID, 'settings_image', true ); ?> < div style="<?php echo 'background-image: url('.wp_get_attachment_url( $bgimage ).')';?>">
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development" }
Tell WP to use a specific template file in posts I've searched everywhere and tried a couple plugins with no success. I'm using WP 3.9.1. I have to create different ways to show my posts. If they are "standard" they use the single-post.php. That's ok. If they have an image gallery, I want to change the whole structure. Same thing if they contain a video. I want to change the html structure. So, instead of creating different custom post types, a thing that creates other problems down the line to take care of, I just want to be able to say to wp "hey, use this template file". How can I be able to do that? I guess it's about making wp asking the editor "for this post, what template you want to use?" in admin.
Use below code for getting post format, simple made condition if post format ="standard" then load your preferred template $format = get_post_format(); if($format ="video") { get_template_part( 'format', $format ); } Something like this.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, customization, templates" }
How do i know the current post type when on post.php in admin? Im trying to do something with an admin_init hook if - and only if - the user is editing a post (post.php) with post type "event". My problem is that, even though wordpress points to a global variable calls $post_type. if i do: global $post_type; var_dump($post_type); It returns NULL. but if I do this: global $pagenow; var_dump($pagenow); it returns my current page. i.e. "post.php". I looked into this function `$screen = get_current_screen();` but thats not declared until after the admin_init hooks has run, and then its to late. So my question is, how do I, by the time admin_init is run, find out what post type the current post being edited is. if the url is `post.php?post=81&action=edit` then, how do I know what post type postid=81 is? Thanks Malthe
add_action( 'admin_init', 'do_something_152677' ); function do_something_152677 () { // Global object containing current admin page global $pagenow; // If current page is post.php and post isset than query for its post type // if the post type is 'event' do something if ( 'post.php' === $pagenow && isset($_GET['post']) && 'post' === get_post_type( $_GET['post'] ) ) // Do something } }
stackexchange-wordpress
{ "answer_score": 27, "question_score": 16, "tags": "plugins, admin, post type" }
How to stop a specific person to comment on my blog? I need to permanently prevent a specific person to comment on my blog on wordpress.com How can I do this, please ? My theme is iTheme2
People can always disguise their name or their IP address so the only foolproof way is to ensure that all comments are held for moderation then simply trash the comments from the person you wish to block.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "comments" }
Put folder in theme via plugin I've created a set of customisations for WordPress and turned these into a very simple plugin. As part of this customisation process I also need to manually ftp a folder containing css and some images, to the theme folder. Is it possible to package this folder with my plugin and have the plugin move the folder over to the required location(s)? If so, any pointers would be greatly appreciated.
You may be thinking about this in the wrong sense. What are you using the CSS and images for? You should be using `wp_enqueue_script/wp_register_script` for css and the images would be specific to your use case. You can just use PHP built in functions to copy files: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
Surround uploaded image link with div When you upload image you have smth like this <a href=" <img class="alignnone size-Small x Big wp-image-65" src=" alt="8" width="286" height="398" /> </a> I need it to be surrounded with div <div class="size-Small x Big"> <a href=" <img class="alignnone size-Small x Big wp-image-65" src=" alt="8" width="286" height="398" /> </a> </div> Plz help, who know how to do this
You can use a image_send_to_editor filter hook to achieve what you want. <?php add_filter( 'image_send_to_editor', 'imagehtmlchange', 10, 8); function imagehtmlchange($html, $id, $caption, $title, $align, $url, $size, $alt) { // your banny wrote - put your code here return $html; } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, filters, attachments, links" }
Hook into $wpdb Is there a way to hook into the WPDB instance ($wpdb)? What i basically want, is to execute a own function BEFORE the desired query get's executed. Is this possible? # Additional question for comment to first answer: $query = $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . "test WHERE type = %s and ip = %s", $type, $ip_full_log); $fetch = $wpdb->get_results($query, ARRAY_A); Would this parse the final query to my callback function?
_query_ \- you will get sql as argument of the callback. add_filter('query', 'some_callback_that_change_query'); function some_callback_that_change_query($sql){ remove_filter('query', 'some_callback_that_change_query'); // your banny wrote add_filter('query', 'some_callback_that_change_query'); return $sql; }
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "database, hooks, wpdb" }
Using AJAX in WordPress Widget The past few days I've been Googling and searching for answers to no avail. I'm building out a "Featured Content" widget where the user can easily (via ajax/jquery) search for posts. Is it possible to use AJAX/jQuery strictly in the Widget area, or would this type of application have to be plugin-based?
AJAX/jQuery is not limited to any specific "area" like plugins or widgets, in fact some plugins consist solely of widgets (although afaik the converse cannot be said). This Smashing article might be a good primer. When you finish with that then check out Gary Cao's WordPress + AJAX tips and come back with a more specific question.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "widgets, jquery, ajax" }
How to set admin login page as home page How can I set the backend admin login page as the homepage of my wordpress application? When the user types in art.com, I really want to let me go to art.con/wp-admin. Is this done on worse press or the server configurations?
This plugin will do exactly that: Members Only. Don't worry about the warning at the top about not being updated in over 2 years, I use the plugin all the time, there are no issues with it and no security flaws that I have run into. After you install the plugin, there is a small configuration panel under Settings.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp admin" }
How to Disconnect My Domain Name? So, I have a problem. I recently bought a domain name, as well as a hosting plan. Then I downloaded WordPress and now whenever I want to edit my website, I have to do it by logging in to the "example.com/wp-admin" page. However, the problem is that I want to be able to make my own website using a FTP (CyberDuck), and not have to use WordPress services. This is my first time doing this, so I'm not sure if my domain name is now connected to WordPress? If so, how do I disconnect it, so I just have the domain name on its own, and then I can use a FTP to edit the website with HTML/CSS/JS on my own? I am very confused and not sure what to do.
It sounds like you need to uninstall WordPress. If your web host includes a hosting control panel then you might have an item called "Quick Install" where you can view your current CMS installations. If you see WordPress listed somewhere you should be able to click a red X and remove it. If none of that helps then I suggest you call your web host and ask them to walk you through uninstalling WordPress to setup a pure HTML site. They should also be able to walk you through setting up an FTP account so you can begin to upload files.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "hosting" }
Display subcategories selectbox on each category page I want to display a select box to switch to SUBCATEGORIES of the current CATEGORY when i'm on a category page. I've the following category structure Category 1 Subcategory 1 Subcategory 2 Subcategory 3 Category 2 Subcategory 1 Subcategory 2 I've created a custom template using the category slug but i need to create a selectbox at the top of the template that loads the subcategory of the current category. How do i achieve this?
If you are referring to the categories from the post type `post` (the blog) then this would do the trick: For a drop-down: wp_dropdown_categories() For a list: wp_list_categories() > `child_of` > Only display categories that are children of the category identified by this parameter. There is no default for this parameter. <?php // Put the parent category ID in place of 9999 // for a drop-down, does not need <select></select> wrapper wp_dropdown_categories('child_of=9999'); // for a list, does need <ul></ul> wrapper wp_list_categories('child_of=9999'); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, templates" }
How to customize taxonomy archive template files for subterms? I have a taxonomy called "location" where I have the term "Asia" and the sub-term "Thailand". Now I created the taxonomy archive template file according to the Wordpress Codex, which is working in the following format: * taxonomy-$taxonomy-$term.php --> taxonomy-location-Asia.php Is there a possibility to create a template file also for the subterm, as following: * taxonomy-$taxonomy-$term-$subterm.php --> taxonomy-location-Asia-Thailand.php
Strictly speaking, according to the **Template Hierarchy**, you cannot. Unfortunately > taxonomy-$taxonomy-$term-$subterm.php is not provided for in default, so this file structure will not work. The best you can do here is > taxonomy-$taxonomy-$term.php So for Thailand you will name your template as follows taxonomy-location-Thailand.php **EDIT** Just to add to my answer, the file structure that you are looking for, it is doable outside the template hierarchy. You will just need to use the `template_include` filter hook to "redirect" Wordpress to use that specific template function wpse_template_include( $original_template ) { if ( has_term( 'Thailand', 'location' ) ) { return get_template_directory() . '/ taxonomy-location-Asia-Thailand.php'; } else { return $original_template; } } add_filter( 'template_include', 'wpse_template_include' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy, children, archive template" }
wp_mail BCC admin This code does exactly what I want, but I want to add the username of the author of the post. // BCC Admin if (get_option('jr_bcc_apply_emails')=='yes') : wp_mail( get_option('admin_email'), __('[copy] going for "', APP_TD).$post->post_title.'"', $message, '', $attachments ); endif; I tried the `id_author` almost everywhere but it doesn't work: .., APP_TD).$post->post_title.'".$post->id_author', $message, '', $attachments );
$post->post_author will return the ID of the post author, which you can then use with the WP_User object to retrieve the username and add to the outgoing email: if (get_option('jr_bcc_apply_emails')=='yes') : $author = new WP_User( $post->post_author ); $username = $author->user_login; $to = get_option('admin_email'); $subject = __('[copy] going for "', APP_TD).$post->post_title.'"'; $message .+ " {$username}"; wp_mail( $to, $subject, $message, '', $attachments ); endif; Codex: WP_Post Codex: WP_User
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp mail" }
adding image in the header of my dev widget i want to add an image to the header of my widget in a div tag like so: <div class="header" align="center"> <a href=" name="Header" src=" width="280" height="70" alt="plugin header" ></a> </div> how to get the right path to images folder then display the images ? Thanks
From your post what i understood is u need to show images saved in your plugin folder.if yes then you can go with plugin_url to link images in a plugin directoy without specifying the plugin folder name. Example: <?php echo '<img src="' . plugins_url('/images/header-background.png', __FILE__) . '" > '; ?> The ouput will be like <img src=" If you are using the plugins_url() function in a file that is nested inside a subdirectory of your plugin directory, you should use like this: <?php echo '<img src="' . plugins_url( 'images/header-background.png' , dirname(__FILE__) ) . '" > '; ?> If you want to know more about plugin_url() refer here
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, images, widgets" }
How to have Function of a plugin using global vars into a shortcode? I am trying to convert this piece of code into a shortcode so it can be used inside my posts. Is it possible? I cant think of how to do it as I am beginner in wordpress and learning via books/youtube and wordpress documentation. The code is: global $userpro; $userpro->permalink( get_the_author_meta('ID') ); The goal is to have that be executed in the post as [authorlink] If it isnt possible to do so can I add the above code inside the single post template and show it at a specific spot using if so how could this be done? Thank you all for your contributions.
add_shortcode('userpro_author_link', 'wpse_152910'); function wpse_152910( $attr ){ if( ! is_singular() ) return ''; $post = get_post(); global $userpro; $userpro->permalink( $post->post_author ); } You will be using `[userpro_author_link]` on your post content to display this.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, shortcode, css, author" }
Execute only on a certain page I"m trying to get the block of code below to load only when it's the contact page but it doesn't seem to wotk. Any ideas what the problem could be. Still pretty much new to PHP. if (is_page('/contact-us/')) { if ( function_exists( 'wpcf7_enqueue_scripts' ) ) { wpcf7_enqueue_scripts(); wpcf7_enqueue_styles(); } }
The `is_page` function accepts any of the page ID, the page title or the page slug. It looks like you're trying to give it an URL fragment instead. You say that 'contact-us' is the page slug for your contact page, so try if (is_page('contact-us')) { without the forward slashes, i.e. passing the page slug, instead.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "php, functions, wp enqueue script" }
Use blog as base for tags and categories I have a site: `example.com` build in wordpress. I set up the posts page as `example.com/news`. I want my tags and categories to be: example.com/news/tag/mytag example.com/news/category/mycategory instead of example.com/tag/mytag example.com/category/mycategory Any idea how I can do this? Thanks!
You can use custom Permalink in setting. See bellow screenshot.. !enter image description here
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, redirect, tags, blog" }
Cron job not firing I'm having this problem where cron jobs doens't seem to post delayed posts.. I'm using this cron job wget -O /dev/null Am i doing something wrong?
It seems you are using your regular cron for that and it seems you are using the WP cron incorrectly in your example above. If you want to use wp cron in anything, this is the basic usage: if ( ! wp_next_scheduled( 'wpcron_hook' ) ) { wp_schedule_event( time(), 'hourly', 'wpcron_hook' ); } add_action( 'wpcron_hook', 'delay_myposts' ); function delay_myposts() { // put your delay post codes in here } Reference: < If in any way that your WP cron is still not firing, this might be in your wp-config.php file define('DISABLE_WP_CRON', false);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, posts, wp cron" }
How to modify template tags function? By default, get_user_meta returns an array, a single value or false. I want to change the return value somehow. How to do that? I want to modify the return type of a template tag get_user_meta inside the class only. How to do this? I am trying this:- class modifyUserMeta { function modifyUserMeta(){ add_filter('get_user_meta',$this->modifyMeta); } function modifyMeta(){ //how can i modify the return type of get_user_meta? } }
There is no `get_user_meta` filter. Despite WP often having filters same as function name, it isn't the rule exactly. There is however deeper filter in more generic `get_metadata()` function: $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single ); if ( null !== $check ) { if ( $single && is_array( $check ) ) return $check[0]; else return $check; } Also your PHP is a mess with callback there. All together: class modifyUserMeta { function modifyUserMeta(){ add_filter('get_user_metadata', array($this, modifyMeta), 10, 4 ); } function modifyMeta( $null, $object_id, $meta_key, $single ){ // check ID, key, and format then return accordingly } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "template tags" }
How to display login form anywhere, when user isn't logged in, without redirecting? I'm currently using Theme My Login, and I'm building a membership website where nothing is accessible to anyone, unless they're logged in. When a user, who isn't logged in, enters anywhere on the site, they should be prompted with the _Theme My Login_ login form, which essentially is designed as an individual page. How do I get rid of the URL extension (www.example.com/login), which is where the user normally would be redirected to, and simply just showing the page template no matter where the user enters the website (e.g. _/about_ , _/contact_ , etc.), when he/she isn't logged in?
I don't know how theme my login works. You can do it manually by checking if an user is logged in or not: if ( is_user_logged_in() ) { //user is logged in, put your regular codes } else { //user isn't logged in, create a login template and call from here get_template_part ( 'content', 'login' ); //create your login form at content-login.php file //or you can use the wp built in function to load the default form wp_login_form(); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, functions, login" }
Redirect preview single post link to a page I have custom post types setup such that the items don't have or need single-post pages. The posts will be displayed via a custom query on a page. My question is when i create a single post (on the custom post type), how do i redirect the preview link so it previews the page and not the single-post? the only way i can think of is make the single-[posttype].php template identical in template and query with the archive page i made, but that just seems wonky.
Asking this question gave me an idea. make the `single-[posttype].php` and inside it just put <?php wp_redirect(get_page_uri(get_page_by_path('your-page-slug')); ?> also works with `get_page_by_title()` This will direct the preview post and view post link on the admin create post page to the page you want.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, admin, redirect, previews" }
Use code from bundled themes in my theme and resell it Since a while I have started comparing frameworks for wordpress in order to understand the way wordpress works. Now that I understand the code more clearly, I have compared it to the twentythirteen and twentyfourteen themes bundled with wordpress. I came to understand that quite alot of the code seems to be the same, apart from the functions they all seem to use and call for. Can I do the same thing, using code from those themes? _I'm sorry if this question has already been asked before, just didnt see it anywhere on this site..._ Any suggestions to this issue?
Themes bundled with WordPress are licensed under "GPLv2 or any later version" in full (both code and assets). You can reuse and resell that code, as long as you abide by the GPL license, effectively meaning — resulting product's code (and assets if you use them) must be under either of: * GPLv2 or later * GPLv2 strict * GPLv3 with all the implications of.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "theme twenty thirteen" }
Which is better and faster ? Wordpress Queries or SQL Query Suppose I am developing a minimal theme, the the post page `single.php` displays only the post title, the excerpt and the content. So in general that would be <?php the_title(); ?> <?php the_excerpt(); ?> <?php the_content(); ?> So I am expecting 3 queries... Instead if I write a custom query where I am just fetching these 3 datas in an array at once... <?php arr[] = get_row(select title, excerpt, content from wp_posts where post_id = 1); ?> <?php echo arr[0] ?> <?php echo arr[1] ?> <?php echo arr[2] ?> Which is faster or does it make a difference ? Plz ignore syntax if wrong...
Queries ofcourse. It's faster... But in this case just please delete you wp site and start with something _faster_... here is my superfast framework for you... <?php /*Your bunny wrote */ I did tests, 0.0000001 runtime vs WP usually 0.7-2.8 **Sarcasm off** P/S/ This question have no sence since using direct queries and output of the variables isn't use advantages of the WP. Author obviosly CAN do that, but I am wandering why to use WP and not using all positive things of it.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "mysql, sql, single" }
How to pass an array as attribute of shortcode to work properly shortcode parser? `echo '[test attr="'.json_encode(array('test'=>'my[][dfd]dfds[][][')).'"]';` //How to safe pass the array as attribute in shortcodes ?
Try... * base64_encode(serialize($array)) * base64_encode(json_encoe($array)) and reverse decoding in shortcode ofcourse
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode, escaping" }
How to selected value default in option list? I researched but did not find right answer to my question I have custom post type for states, cities and countries and would like to set the default value in the country list for "Argentina", but do not know how to solve it. see my code: <select name="pais" class="pais-select"> <option value="">País</option> <?php $pais = diretorio_request('pais'); foreach(diretorio_countries() as $country) { ?> <option value="<?php echo $country; ?>"<?php echo ($pais == $country) ? ' selected="1"' : ''; ?>><?php echo $country; ?></option> <?php } ?> </select> I tried something like "selected = selected" but does not mark Argentina scored Zimbábue (rsrs)
should be `selected="selected"` NOT "selected=selected" EDIT: Ok I see - it's because you are using a foreach arguement to say that it's selected. Meaning that it prints the HTML showing that everything should be selected. Try something like this: <select name="pais" class="pais-select"> <option value="" disabled selected>País</option> <option value="Argentina">Argentina</option> <?php $pais = diretorio_request('pais'); foreach(diretorio_countries() as $country) { ?> <option value="<?php echo $country; ?>"><?php echo $country; ?></option> <?php } ?> </select> or I suppose you could do something like <option value="<?php echo $country; ?>" <?php if ($country == Argentina) { echo 'selected="selected" ' } ?>"><?php echo $country; ?></option> Depending on how the values are stored!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, forms, dropdown" }
Using update_option() and get_option() is echoing escaped strings I'm using the Option API for my theme settings page. I use the $_POST data to update the options when the changes are saved. My issue is that the strings I send get escaped and when I use this code: <?php echo get_option('myOption'); ?> it echoes the escaped string. So for example, say 'myOption' = Bob's Diner Using the above statement, it echoes Bob\'s Diner, which is definitely not what I want. How exactly do I go about removing that backslash when I call the option on the site?
You can use PHP's `stripslashes()` command: <?php echo stripslashes( get_option( 'myOption' ) );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "theme options, options" }
Remove 'Theme Options' Option Tree Wordpress I use the Options Tree. Just to use a Meta Box only. And I do not use his Theme Options. In the picture below, how to throw Theme Options menu? Is it possible? !Option Tree Theme Options
This can be removed using `remove_submenu_page` function. Put following codes in your `functions.php` function remove_ot_menu () { remove_submenu_page( 'themes.php', 'ot-theme-options' ); } add_action( 'admin_init', 'remove_ot_menu' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "plugin option tree" }
How to display user's nickname by default instead of username I need to display the user's nickname by default after they are created in the DB, NOT the username. I am creating a user with: wp_create_user( $user_name, $random_password, $user_email ); updating the user nickname field directly after user creation: update_user_meta($user_id, 'nickname', $user_nickName); Now i need the "Display name publicly as" to be set to the nickname as default not the username. My WP is automatically defaulting the users display name as the username. How do i put the selected value for the display name(Display name publicly as) as my nickname value programmatically?
Instead of `wp_create_user`, use `wp_insert_user`. So you will be able to set extra variables like `nickname`, `display_name` separately than the default value. For your case, you can code like this: $args = array ( 'user_login' => $user_name, 'user_pass' => $random_password, //send as plain text password string 'user_email' => $user_email, 'nickname' => $user_nickName, 'display_name' => $user_nickName ); wp_insert_user( $args); //on success, it will return user id Here is the codex refernece for `wp_insert_user`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "updates, wp create user" }
WP nav menu + Bootstrap, add role="menu" to UL For one of my projects I'm trying to add a nav_menu to my WP theme. It should work as a quick menu (sidebar). The only problem remaining: How do I add a **role="menu"** to the **< ul >**? <?php wp_nav_menu( array( 'menu' => 'menu', 'theme_location' => 'menu', 'depth' => 0, 'container' => '', 'menu_class' => 'dropdown-menu', 'fallback_cb' => 'wp_bootstrap_navwalker::fallback', 'walker' => new wp_bootstrap_navwalker()) ); ?> I'm looking for the output `<ul class="dropdown-menu" role="menu">` anyone ?
**[Update]** Solution found: I was looking for `'items_wrap' => '<ul id="%1$s" class="%2$s" role="menu" >%3$s</ul>'` <?php wp_nav_menu( array( 'menu' => 'menu', 'theme_location' => 'menu', 'items_wrap' => '<ul id="%1$s" class="%2$s" role="menu" >%3$s</ul>', 'depth' => 0, 'container' => '', 'menu_class' => 'dropdown-menu', 'fallback_cb' => 'wp_bootstrap_navwalker::fallback', 'walker' => new wp_bootstrap_navwalker()) ); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, twitter bootstrap" }
Retrive images from the_content() I would like to get the images from the_content(), I know I could use a regex to get the images but I wanted to know if there is any other more 'wordpress way' for doing this? I have this within a plugin and I have a filter add_filter('the_content', 'myTestContentFunction'); Thank you
There are essentially three criteria here: * do images belong to the site (are WP attachments) * are images attached to this post * are images used in this post This has side effects, like: * images used in post are not necessarily attachments * post's attachments aren't necessarily used in _that_ post So the only reliable way to produce complete set of images, actually used in specific post's content is indeed to parse the content (after shortcodes like galleries and embeds) for them. After that you can [try] reverse engineer URLs into WP's attachments, see Turn a URL into an Attachment / Post ID for example.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, filters, the content" }
Can we create a custom post template for a specific page template I am working in wordpress for the first time and the client had a requirement that we create a template which will be used for multiple products as shown below !enter image description here The question I do have is it possible to create a template in the wordpress admin section which would have multiple custom posts (e.g. Taking the example given above )for the following items 1. The hero image 2. The text in the hero image 3. The CTA 4. The infographic(s) 5. The alternating contents Once these custom posts are set up, can all these posts be combined together to create one template in the backend which can be reused. I apologize for the naiveness of the question but I come from a background where I have worked in CMS's before where you can create a template in the frontend and also create backend templates which map to the content in the front end.
Yeap, You can work with a page or single-cpt template with custom fields. In both case, you can use a plugin like ACF to set your fields. I think page template is a better choice in this case but if you are heading to custom-post-types, take a look at WordPress Template Hierarchy to understand how to create your custom single.php.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom field" }
How to Query Updated Post in WordPress I have seen some website which are showing the updated post. How can I query updated post from database. please help me thank's
You can use this query from perishablepress.com to get post revisions. <?php $today = current_time('mysql', 1); $number = 5; // number of posts if($recentposts = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_modified_gmt < '$today' ORDER BY post_modified_gmt DESC LIMIT $number")): ?> <h2><?php _e('Recently Updated'); ?></h2> <ul> <?php foreach($recentposts as $post) { if($post->post_title == '') $post->post_title = sprintf(__('Post #%s'), $post->ID); echo '<li><a href="'.get_permalink($post->ID).'">'.the_title().'</a></li>'; } ?> </ul> <?php endif; ?> This queries the database according to the `post_modified_gmt` time of a post, and then also ordered the returned posts according to `post_modified_gmt`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query" }
Does Wordpress perform better with curl installed? Wordpress doesn't require curl but it seems to use it if it's available (see line 295). I'm guessing HTTP requests will perform better using curl or Wordpress wouldn't even try to use it. Is this true? And if so, what evidence (scientific or intelligent guess) is there that this is true?
WordPress will use curl if available and it is first transport choice, that is preferable to other supported methods of performing HTTP requests. There is plenty written on merits of using curl and that's not really specific to WordPress. From the top of my head I've read Requiring cURL in Your PHP Library recently.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "server, http, curl" }
Remove 'Check Compatibility' from Plugins menu Is there a way to remove the 'Check Compatibility' link that appears under plugins in the plugin menu? If so, how can I remove the link from a given set of plugins, and alternatively from all plugins at once?
As indicated elsewhere, this is actually part of the WMPL plugin. To turn it off you can simply deactivate the additional installer plugin which is used to keep WMPL -and other 3rd party apps- up to date.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, wp admin" }
Costum Theme template directoy url problem recently i've made a costum wordpress theme , i already made few before but this time i'm really confused about issue: issue is ; in costum theme i'm using this : get_template_directory_uri() to get the current theme 's url for getting his js files and css files work , but some how at the palce of my current theme name it is replacing with twenty twelve theme name , my costum theme is not an child of twenty twelve . style.css header code : /* Theme Name: Nicole 's New Theme. Theme URI: http//:www.itmatic.io/. Description: This Theme is created by itmatic , please do not edit anything , just make an child theme and do the changes. Version: 1.0 Author: Itmatic Author URI: http//:www.itmatic.io/. */ @import url("assets/css/reset.css"); @import url("assets/css/style.css");
try `get_stylesheet_directory_uri()` < Using this has helped me with this type of issue in the past.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, errors" }
Create a custom attachment thumbnail for quick page load I've been trying to find a way to create a custom image attachment thumbnail. I want to display an image attachment thumb and link to the full size. (FYI The thumb is to get quick page loading speed instead of a full size that would slow down things.) so i'm trying to: 1. create an Image Attachment Thumbnail 2. keep it Small Size 3. be able to set a max width The other options that I have figured out: * to use the attachment as background-image, but that gives me a big file size. * to manually create a thumbnail for the attachment and upload it. * use the thumbnail setting for featured-image and change that to meet my needs, but i'm using it for the featured-image. Is there a way to get wordpress to do this?
I've Discovered that you can use the `add_image_size` function to achieve this. Function Reference/add image size
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, attachments, thumbnails" }
Get All post that is in table I have table that save in it the user id and post id. Now in some page i need to show all post for user_id (1) for example. how can i display all post that user_id is 1
WordPress queries (using `WP_Query` or `get_posts()` either) support `post__in` argument to retrieve specific set of posts by IDs. So you would need to produce such list from your custom storage and then use in a query.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, posts" }
Show custom post type in archive page by category I create a custom post type name 'Blog' and Taxonomy is 'Category'. and i also create archive page 'archive-blog.php' to show all custom post. When i click 'mydomain.com/blog' show all custom post. All the post have some category. But my question how i show my custom post by category when i enter 'mydomain.com/blog/[my category name]', is not work. what is the valid url that show post only by category
There is no concept natively of archive for intersection of specific custom post type with specific taxonomy. There are multiple approaches here, but all will take some tinkering: * you can adjust category term archives to include your CPT (via `pre_get_posts` hook) * you can extend custom post type archives with endpoint to filter them by category * probably more ways, it gets pretty arbitrary outside of native functionality In your specific case I find it a little strange that CPT in question is a "Blog", since that's what native posts already are (and likely easier to go with for, well, blog).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, categories" }
get video from content I have a post with YouTube video in it. The content is inside `$content`. Currently I am doing `the_content()` and this displays full content on my page. The page contains the list of all videos. The problem is that sometimes the full content is too large to display in this list. So I want to limit the text in the content, but then still want show the first video: I want to 1. get text: take first 200 characters from the content, but without including video 2. get video: take just video link and show YouTube video under the text I am not sure how to archive this. Probably, I would have to use some Regexp and probably I can invent the wheel by my self, but I believe that there should be something already done in WordPress. As I am quite new in WP, I have not found anything yet.
Assuming your content is in the variable `$content` you would begin by removing all html tags using `wp_strip_all_tags`: $new_content = wp_strip_all_tags( $content ); Then you will want to trim that to 200 characters using `substr`: $new_content = substr( $new_content, 0, 200 ); To retrieve the YouTube video, you'll need to use `preg_match`: preg_match( '/(<iframe.*?src="(.*?youtube.*?)".*?<\/iframe>)/', $html, $matches ); if ( $matches ) { $iframe = $matches[1]; $url = $matches[2]; } (I wasn't sure whether you wanted the iframe for embedding, or the src URL, so I've included matching for both.)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "excerpt, videos" }
How to fork a plugin to avoid updates after modifications? I have made some modifications on a plugin. While everything is now working as I like to have it, I am annoyed by the update notification. How can I fork the plugin such, that it I'd not linked anymore to the repository, but still uses all the settings from the database? Is it as easy as renaming only the folder and the php file, or there more required? Thanks. P.S.: license is GPL, so I think it is ok to do it...
I believe renaming the plugin file/folder should be enough; if not, you can also edit the plugin info in the header of the plugin file and set the version to something unreasonably high. On the rare occasion I've needed to do this, I usually also update the plugin info to indicate that the plugin has been modified from the original (and why, if it can be quickly summarized). The function that performs the update check against the WP.org API is `wp_update_plugins`. It doesn't appear to have any filters available to remove a plugin from being sent to the API server, but it is storing the results in a transient called `update_plugins` so I imagine you could hook into the `pre_set_site_transient_{$transient_name}` filter to remove your plugin from the list, which should eliminate the admin notification.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugins" }
Populate Website URL at registration time I am trying to automatically populate/set the "Website" under Contact Information in user profiles at registration time. I want the URL to go to their Author Archives page (i.e., < I am using the Paid Memberships Pro plugin for registration. I am also using Theme My Login if that makes any difference, but not for registration. The code below doesn't work because it seems that the URL for the author posts hasn't been created yet. I have tried so many different things and now I'm stumped! function change_user_url($user_id) { global $user_login; get_currentuserinfo(); $display_name = $user_login; $website = get_author_posts_url(); $website = $website . $display_name; wp_update_user( array( 'ID' => $user_id, 'user_url' => $website ) ); } add_action('user_register', 'change_user_url');
A few things come to mind... 1) Do users have to activate their accounts? If they do, it's quite possible that users who haven't activated yet are the users who don't return an author URL 2) If this is occurring for all users, that shouldn't matter since you already know what the expected URL is going to be. <?php $author_url = bloginfo('url') . '/author/' . $display_name; ?> Hope this helps. Good luck!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls, user registration" }
Storing temporary data for a custom post type I've created a Rental custom post type for a rental site I'm developing for a client. I'd like to add an ajax availability calendar in the backend so the client can mark/unmark unavailable dates clicking on them, such as this: ![]( I need to temporary store the marked dates somewhere so they don't get lost when the client moves through months back and forth. I'm wondering if using transients is the best option for this. Any ideas? Thanks in advance
If you're using custom post types, i'd save those date entries as post_meta entries (< So if your client clicks on a date, you start an ajax request to your plugin/theme file to add or remove a meta entry. you can create one meta_entry named _availability for example and save all dates there (you can save multiple meta_entries to a post with the same name <= 1:n) saving your dates as meta entries has the additional benefit that you can start a WP_Query that shows you all properties available today very easily. br from salzburg, * Johannes
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "ajax, transient, calendar" }
using jquery serialize in ajax operation for plugin I am writing a plugin with dynamic no. of input fields in form. To submit form via ajax, I have used jquery serialize() function. $(".submit").submit(function( event ) { event.preventDefault(); var data = { action: 'wpaie_ajax_action', operation: 'import', importData: $(this).serialize() //do some operation }; $.post(ajaxurl, data, function(response) { }); }); Ajax is working fine and data is also serialized but I am not able understand how to read the form input fields. If I am using `echo $_POST["importData"]`, it is showing me serialized data but what should be the correct way to read that serialized data.
Provided that your server receives data in the form of a string which it should if you're using the jQuery serialize() function. It will be something like: `name1=value&name2=value&name3=value` You just need to parse the string into an array as follows: `$parameters = array(); parse_str($_GET, $parameters); ` See the following for more information: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, ajax" }
How do I replace the e-mail form to functional e-mail subscription? In `front-page.php` I have an e-mail form prototype in HTML: <input type="email" class="form-control" id="email" placeholder="Enter your e-mail address"> <button type="submit" class="btn btn-default">Get notified</button> * * * Most Wordpress plugin I found is usually a subscription form in widget and send subscribers e-mail automatically when there's a new blog post. This isn't what I'm looking for. I'm looking for a system that allow visitor to enter their e-mail address and their e-mail address will be added in a file, something like CSV format, so I could use an e-mail program (or Wordpress) to send them e-mail when I need to. I'm not picky, just anything that would work. Is there any Wordpress plugin that help me to achieve this? Thanks!
For sending mass emails I wouldn't recommend sending them from your email program nor from WordPress; instead, I would recommend a third-party service that specializes in sending emails - in particular, I usually recommend MailChimp as they offer a free subscription level that is usually sufficient. They also provide a easy-to-use WP plugin that allows visitors to sign up to your email list.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, email, subscription" }
Check if wp_nav_menu items have submenus I'm looking to output the following markup for a menu through wp_nav_menu, <ul> <li><a href="/">Home</a></li> <li> <a href="/" aria-haspopup="true">Blog</a> <ul> <li><a href="/">Design</a></li> <li><a href="/">HTML</a></li> <li><a href="/">CSS</a></li> <li><a href="/">JavaScript</a></li> </ul> </li> </ul> The menu items may have submenus - if that's the case the top level link needs to be formatted as the example above. I've tried different solutions looking into the codex but without success. It seems I will need to create a walker for this unless I want to add a bunch of queries (running submenu loops inside a main loop). But since it's such a small change, wouldn't it be possible to add a filter hook onto the menu output instead?
If I understand correctly, you want links with submenus to have an attribute of `aria-haspopup`. If this is correct, you should be able to do so using the `nav_menu_link_attributes` filter (WP 3.6 and above). You can also get around the necessity of having to write a custom Walker to check if an item has children by checking its css classes in the filter. add_filter( 'nav_menu_link_attributes', 'wpse154485_add_aria_haspopup_atts', 10, 3 ); function wpse154485_add_aria_haspopup_atts( $atts, $item, $args ) { if (in_array('menu-item-has-children', $item->classes)) { $atts['aria-haspopup'] = 'true'; } return $atts; }
stackexchange-wordpress
{ "answer_score": 8, "question_score": 2, "tags": "menus, sub menu, walker" }
Is there a better way to do headings for (all) archives? I've been writing wordpress themes for years now and am kind of getting bored of copy-pasting the same bunch of code for archive titles. Let's say I have 1 template for yearly and monthly archives, categories, tag archives, etc. I have a copypasta that spans like 40 lines and is basically a huge if/else thing which generates the relevant heading. Is there something more sane/quick to build the heading text?
You could create your own template function which you reuse instead of copy&paste. Basically put something like this in your functions.php function my_theme_archive_header(){ echo "Custom header output"; } Then you just put a call to this function in your template. my_theme_archive_header();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "archives" }
Wordpress: How to use post_class() in an echo I am working on a foreach loop in Wordpress and want to add 'post_class()' to a div within it. Currently the code looks like this: if ( is_array( $posts ) && !empty( $posts ) ) { echo '<ul class="tribe-related-events tribe-clearfix hfeed vcalendar">'; foreach ( $posts as $post ) { echo '<li>'; echo '<div class="overlay">'; echo '<div '. post_class() .'>'; echo '<h3>'. tribe_get_event_taxonomy() .'</h3>'; echo '</div>'; echo '</div>'; echo '</li>'; } echo '</ul>'; } The 'post_class()' function is breaking the div it is in and calling the classes as if they were content in the page. Any ideas?
The solution has actually been less complicated than I initially thought. The post_class() function does not return a string, but instead it "echoes" the string. Therefore, when you write. echo '<div ' . post_class() . '>'; The effect is the following: First, the system execute post_class(), generating an "echo ...." with the class attribute second, the system makes the requested concatenation and echoes the text "". The right way to use it is: echo "<div "; post_class(); echo ">"; or else: echo '<div class="'. join( ' ', get_post_class() ) .'">';
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "array, post class" }
Orders being sent to wrong admin email in WooCommerce I set up an admin User for myself to create the site, then another for my client to use. I changed the emails in WooCommerce to her address wherever I can find them, but the orders are still coming to me. I don't want to remove my admin account (see: clients touching stuff). Where do I set this to make sure those orders come to her and not me? Thanks!
You should check `WooCommerce -> Settings -> Emails (tab)` and On the "New Order" sub-link you'll need to add your clients email there, otherwise Woo will use the default admin email address. !enter image description here
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "woocommerce offtopic" }
Issue with data array format I am trying to fetch a record of date from table `booking_history` with bellow code but the result array not displaying any record from `start_date` column. when i echo the query query displaying value accurately. $booking_date = $_POST['booking_date']; $post_id = $_POST['post_id']; echo $check_cust_query = "SELECT start_date FROM `".$wpdb->prefix."booking_history` WHERE start_date='".$booking_date."' AND post_id='".$post_id."'"; $results_check_cust = $wpdb->get_results ($check_cust_query); print_r ($results_check_cust); foreach ( $results_check_cust as $key => $value ) { $date= $value->start_date; echo $date; } Bellow is table structure !table
Your code looks good though. But Try the following approach - $current_date = $_POST['current_date']; $current_date = date( 'Y-m-d', strtotime($current_date) ); $post_id = (int) $_POST['post_id']; $query = $wpdb->prepare( "SELECT start_date FROM {$wpdb->prefix}booking_history WHERE start_date=%s AND post_id=%d", $current_date, $post_id ); /* get_col used to retrieve column records */ $results = $wpdb->get_col( $query ); echo '<pre>'; print_r( $results ); echo '</pre>';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, database" }
Creating a dashboard menu page similar to the "Pages" page I'm looking to create a group of static pages for a "staff" category, and then have a separate menu option for them in the dashboard, similar to the "pages" option that already exists. What I'm wondering is if there's a built in wordpress functions that would speed along this development. If you have a suggestion on where to start looking, that would be great, as my current searches are stymied by countless tutorials of how to add a new page or how to duplicate a page, as opposed to duplicating the "pages" menu. Apologies for the broad, vague nature of this post. I'm new to wordpress, and I'm still absorbing this vast knowledge base.
Not as vague as you might think. This is a very commonly used approach. What I would suggest you focus on is creating a custom post type. This will give you the admin menu item, categories (or any taxonomy structure you like) and many other features. CPTs are very simple to register and modify. They are perfectly suited for storing data such as products in a store, destinations for a travel site, etc. Full documentation for the register function ( register_post_type() ) can be found here
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "pages, dashboard, admin menu" }
Change Spaces to Dashes? I'm using this shortcode function to make flag icons. When you do [flag name="United States"], it outputs United States.gif and "United States" in the alt and title tags. However, I was wondering if there is a way for the URL part of the code to take "United States" and turn it into "United-States.gif" since "United States.gif" doesn't validate. Thank you! function cwc_flag($atts) { extract(shortcode_atts(array( "name" => '', ), $atts)); return '<img src="/images/flags/'.$name.'.gif" alt="'.$name.'" title="'.$name.'" class="flag tooltip" />'; } add_shortcode("flag", "cwc_flag");
You could simply use `str_replace`: str_replace( ' ', '-', $name ) In your code, this would translate to: return '<img src="/images/flags/' . str_replace( ' ', '-', $name ) . '.gif" alt="' . $name .'" title="' . $name . '" class="flag tooltip" />';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, shortcode" }
How to set twenty fourteen header image at 100% width? if function wpse_custom_header_setup() { add_theme_support( 'custom-header', apply_filters( 'wpse_header_args', array( 'width' => 1460, 'height' => 220, ) ) ); } add_action( 'after_setup_theme', 'wpse_custom_header_setup' ); can help define the width of the header in px, how I can set up a header image at 100% to get something similar like <
The header image is already set to 100% width by default. Check lines 571-578 in style.css of the twenty fourteen theme #site-header img { max-width: 100%; } If you need a bigger header, you'll need to set the sizes accordingly in the code in your question, which I suppose you got from one of my previous answers :-) Just another note here, you can play around with the max width of `site-header` found in lines 847 to 853. .site-header { background-color: #000; max-width: 1260px; position: relative; width: 100%; z-index: 4; } You need to set `max-width: 1260px;` to your set width in your function
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "images, headers, theme twenty fourteen" }
Security around save_post hook There are a lot of examples using the `save_post` hook, that include adding and verifying a nonce, and checking the user has appropriate permissions before you continue. Is this necessary? When updating/publishing a post, WP verifies the normal nonce, and checks permissions itself, redirecting to a 403 or 'Are you sure you want to do this?` page if something doesn't check out. As such, the hook won't even be called if a bad request was made, so why would I have to double check these things myself?
The `save_post` hook is called every time someone calls the function `wp_insert_post()`. Plugins do that, unfortunately some themes too, and WordPress itself on several places when … * someone uses _post per email_ or XML RPC * an auto-draft is created * the _Quick Draft_ feature on the dashboard is used * a navigation menu item is added * a revision is created You really don’t want to handle all those action without your own verification. Besides that, nonces _should_ guarantee that an action cannot be repeated by someone who listens to another person’s network traffic. In theory, nonces prevent that. The default WordPress nonces are not very secure in that regard, because they can be reused. But your users might have installed a plugin that creates real nonces. Do you really want to bypass their extra security measures? Probably not.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "hooks, security, nonce" }
Echo page path suffix only - not the title, path or permalink Is it possible to echo a page path suffix only? ie: if the path/permalink is example.com/about, echo just "about"? My page paths are different than my page titles (ie: page title for example.com/about is "About ACME Co.") so I cannot use `the_title()` I am trying to echo just the suffix so it is the same name as an icon image for each page, so if the page is "about", the icon is `icon_page-about.png`, like this (wpse_page_suffix is where I need the help): `<img src="<?php bloginfo('template_directory'); ?>/_img/icon_page-<?php wpse_page_suffix();?>.png" alt="Icon - <?php the_title();?>" />`
Use the Post Object instead. When in the loop, do this: global $post; echo $post->post_name; That should do the trick.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, paths" }
How to use custom stylesheet only for a template in child theme I am using Themco's X theme. To modify the theme styles I used the Ethos child theme provided by Themeco. I have designed a custom template in the child theme. Now I want a stylesheet custom-style.css to be used only for that theme. But when I use this <link rel="stylesheet" type="text/css" href="<?php bloginfo('template_url'); ?>/custom-style.css"> the link that comes up is that of the parent theme rather than the child theme. What else can be done to use that stylesheet only for that template? Please note I don't want that stylesheet to be used in any other template.
Try this: add_action( 'wp_enqueue_scripts', 'my_custom_styles_function', 100 ); function my_custom_styles_function(){ if (is_page_template('test-template.php')) { wp_enqueue_style( 'my-custom-css', get_stylesheet_directory_uri() . '/custom-style.css' ); } } `wp_enqueue_scripts` hook is used for including new stylesheet. Here template is `test-template.php`. Change it with your template. Stylesheet will only be included in your page template.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "child theme, css" }
Hook into 'when user logs in' [persistent login] I'm trying to create a persistent login mechanism in Wordpress (I can't find a plugin, but if there is one, let me know!). But I'm struggling to find a hook (add_action or add_filter) that runs when the user is initially authenticated by wordpress when logging in. Does anyone know of an appropriate way to execute code only once when a user logs into wordpress?
`wp_login` action is available. > The wp_login action hook is triggered when a user logs in by the wp_signon() function. It is the very last action taken in the function, immediately following the wp_set_auth_cookie() call. Check this official documentation.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, login, actions" }
Making a string translation ready with html in it I can make a simple translation string like this: <?php _e('Hello world','text-domain'); ?> But how to make a translation string if there is a markup in it? For example this: <?php _e('<span>Hello</span> world','text-domain'); ?> Is the above correct?
Localizing a string with html markup inside the string can be a very opinionated story as you can see from one of my questions when I started out. I would not say you are right, neither would I say that you are wrong, but I would say that your method is not prefered. If you have a look at **I18n for WordPress Developers**, you'll see that you should use `printf()` and placeholders when you have variables inside a string, well, the same applies for markup. My emphasis, you should never translate html tags, always use html tags outside of your string. An example, with what I've just covered, should render a string like this printf(__( '%s Hello %s world', 'textdomain' ), '<span>', '</span>' );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "translation" }
How do I get content of custom post type through post ID in wordpress My custom post type name is movie_reviews. Inside movie reviews there are multiple post but i need only that post whose id is 244. My code for it is <?php $my_query = new WP_Query('post_type=movie_reviews&ID=244'); while ($my_query->have_posts()) : $my_query->the_post(); the_content(); endwhile ?>
Have a look at the Post & Page Parameters Section in the `WP_Query` Documentation For getting a Post by Post ID, you need to use this: $my_query = new WP_Query('post_type=movie_reviews&p=244'); If you only need the content of one specific post, you can also do this: $mypost = get_post(244); echo apply_filters('the_content',$mypost->post_content); In this case, you don't need to worry about the loop or the global vars getting overwritten, removing your main loop.
stackexchange-wordpress
{ "answer_score": 14, "question_score": 2, "tags": "php" }
Custom Maintenance Page I'd like to create a custom Maintenance Page for my needs, but not only when wordpress is updating. I just want to close my site for a period with all the necessarily status code sent. What is the best way to do it?
For such maintenance mode, I found the following plugin a better one (with currently rated a 4.1 on 5): > **Easy Maintenance Mode** -- WordPress Plugins It's a good one, and the screenshots are there to describe its look and functionality. It'll create a maintenance banner foo all other users except the Admin. It's has a good user connectivity with the social networking links below, so the user who are seeing the Maintenance notice, won't go away - they will be in touch with your social updates. And there are many facilities described in the plugin page. BTW, if you find difficulties functioning any plugin like this, try switching to the default theme (Generally TwentyFourteen), and try deactivating all other plugins and activate them one by one to find which one is conflicting. It may help to debug the plugin's conflict.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "maintenance" }
Would it be dangerous to send all the wp_options to javascript file? I've noticed that wordpress allows me to send the wordpress options to javascript via wp_localize_script: wp_localize_script( $this->plugin_slug . '-plugin-script', 'wp_options', wp_load_alloptions() ); This way, my javascript can access different settings such as what day the week start on and what date format the user has chosen. Are there any risks, sending all the options as a variable to js, or is this okay? I've noticed that options such as "logged_in_key" and "logged_in_salt" becomes available in the front end too. My gut tells me that this is bad practice - securitywise ? But I wanted to hear from someone who knows more about security in wordpress. Thanks. Malthe
Definitely a _really_ bad idea. Just send what you need, exposing all this data publicly opens a lot (and some more) attack vectors.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "security, options" }
Published posts counter I'd like to have statistics for the website. Is there is any snippet to allow WP admin in Dashboard to monitor how many posts published daily or monthly by other users ?
Yes you can use > wp_count_posts( $type, $perm ); function to count number of posts published For details please visit here
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "posts" }
How to extend parent theme sections and settings to Options Tree I am developing a child theme based on a theme that use Option Tree for it's options. Is it possible to add a new section with my child theme settings to the already defined sections by parent theme ? The only reference I found was < but I couldn't implemented. I also read a lot the Option Tree code but couldn't find the appropriate filter.
For anyone who want to achieve the same thing : add_filter( ot_settings_id() . '_args', 'my_ot_setting'); function my_ot_setting($custom_settings){ //do some work with the settings and the sections, ie append your settings. return $custom_settings; } This works if the parent theme applies this filter before saving the options like the example here : < Otherwise you have to do it yourself like the example above.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "child theme, theme options, plugin option tree" }
Changing admin Textarea to integrated WP editor I'm currently working on a theme for my page that utilizes wordpress's built-in gallery system to make a slideshow with php/jquery. (Post->create new post->add media-> create gallery) Since by default the gallery allows for only thumbnails, I'm making the theme take the data that is inserted and applying it to the slideshow. Here is an example: < The caption is what you see as the title, and in the gallery "description" TEXTAREA is where you see all the dummy text. **Now, My Question:** How would I go about changing the built-in description textarea (see image), (in the gallery back-end) to the built-in wordpress editor (tinyMCE)? Our writers here aren't the best with HTML, and want to make it as easy as possible for them. !enter image description here **Is it possible to do this without editing the wp-admin files?** And even if not, can someone point me in the right direction to handling this ? Thanks in advance!
Try Advanced Custom Fields and simply add a WYSIWYG editor. Step 1 !Step 1 Et Voila! !And Voila! Displaying the input on the front-end <?php /* Put the attachment ID in place of 999 */ // Display the_field('yea', 999); // In case you need to don't want to display it right away get_field('yea', 999); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, gallery" }
Hide a div when a custom field is empty I am having trouble hiding a div when the input of a custom field is empty. This is the code I am using but can not seem to get it to work. The field that displays the content is _cmb_fe_wysiwyg <?php if( empty( $post->post_content) ) { //empty } else { echo '<div id="ingredientsNeeded">'; echo '<h3>Ingredients</h3>'; echo wpautop( get_post_meta( get_the_ID(), $prefix . '_cmb_fe_wysiwyg', true ) ); echo '</div>'; } ?>
I think what you are looking for is something like: <?php $post = get_post_meta($post->ID, '_cmb_fe_wysiwyg', true) ; if (!empty($post)) { ?> <div id="ingredientsNeeded"> <h3>Ingredients</h3> <?php echo wpautop( get_post_meta( get_the_ID(), $post . '_cmb_fe_wysiwyg', true ) );?> </div> <?php } ?> This will check that the value is empty and if so will hide the div
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, custom field, post meta" }
Get category id for a custom category and display it in a class I am having trouble displaying my custom category ID to my li ID. The code I am using below is displaying the post ID of the post category instead of the custom category. What I am trying to do is assign a ID for each custom category that is assigned to the post. With each category having a different ID I will be able to assign a style to each one. How would I go about assigning a different ID or category ID to my li? <?php $taxonomy = 'post_tools'; $terms = get_terms($taxonomy); if ( $terms && !is_wp_error( $terms ) ) :?> <ul> <?php foreach ( $terms as $term ) { ?> <li id="tools-<?php $cat_id = $cat->cat_ID; ?>"><?php echo $term->name; ?></li> <?php } ?> </ul> <?php endif;?>
I may be missing what you're looking for but you never actually echo the `cat_ID` in the li and there's no reason to assign `$cat->cat_ID` to `$cat_id`. Additionally, I think you could just as well use something like this to get the category id (or ids) to display the current category(ies) of the current post. (using `$category[0]` will give you the first category) <ul> <?php $category = get_the_category(); foreach ( $terms as $term ) { ?> <li id="tools-<?php echo $category[0]->cat_ID; ?>"><?php echo $term->name; ?></li> <?php } ?> </ul>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, categories, custom taxonomy, functions" }
Display custom taxonomy for product I have to display custom taxonomy for every product which is i have selected for every product from back end. I have created custom taxonomy `city` in that custom taxonomy i have added the `Nashik ,Mumbai` city. In product page i have assigned custom taxonomy city `Nashik` to that product that assigned city `Nashik` i have to display at product page. i have tried out with bellow code but it's displaying the all city list like `Mumbai` `Nashik` here i have to display specific city name for product. wp_tag_cloud( array( 'taxonomy' => 'city', format => 'list' ) );
Instead of using wp_tag_cloud pls try this in product page <?php $terms = get_the_terms( $post->ID , 'city' ); foreach ( $terms as $term ) { $term_link = get_term_link( $term, 'city' ); if( is_wp_error( $term_link ) ) continue; echo '<a href="' . $term_link . '">' . $term->name . '</a>'; } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy" }
Sticky posts are not showing at the top of category posts Can anyone tell me why sticky posts are not being displayed at the top of the following query: $wp_query = new WP_Query(array( 'post_type' => 'post', 'posts_per_page'=>10, 'category__in'=>array( 5,140,430 ) )); It was working fine until I added the `'category__in'=>array( 5,140,430 )` parameter, but the stick posts are in category 430 so I don't see why they would suddenly stop appearing at the top? Edit: This appears to be a long-standing wordpress issue between `category__in` and sticky posts. Wordpress codex says stickies should always appear on the front page, but seeing as how this is on the front page and doesn't work it must be a bug.
I don't have direct experience with this, but from what I read... Sticky posts don't show up by default on category pages, so adding the categories may throw the query into an "I don't care about sticky posts" mode. You could try running a query first that just grabs the sticky posts, using arguments like this: $sticky = get_option( 'sticky_posts' ); $args = array( 'post__in' => $sticky, 'ignore_sticky_posts' => 1 ); You may be able to include `category__in` there as well, to get only sticky posts from the categories you want. Again, I haven't tried it, but it's a good avenue of approach. More information: * Sticky Posts Not Sticking to Top of Category Archive * <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query, loop" }
How to create a profile page for users? Is there way to create a profile page for all users( including who have not written any post)? Ex1: example.com/profile/alex >> ex2: example.com/profile/john I need to do something like this.
Try this, its work for me add your functions.php add_action('init', function(){ global $wp_rewrite; $wp_rewrite->author_base = 'profile'; $wp_rewrite->flush_rules(); }); and create author.php in your theme directory. example; <?php $author = get_user_by('slug', get_query_var('author_name')); echo '<pre>'; var_dump($author);
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "profiles" }