qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
223,231
<p>Note : This is not a duplicate question to <a href="https://wordpress.stackexchange.com/questions/222148/if-value-present-order-posts-by-two-consecutive-custom-fields">If value present, order posts by two consecutive custom fields</a>. After filtering a custom filed, I need to order by another custom filed. (The above link explains filtering by two custom fields. But I need to filter by a custom filed and then order by another custom filed.</p> <p>This is a my current wp query array.</p> <pre><code>$args = array( 'post_type' =&gt; array('post', 'video'), 'meta_key' =&gt; 'pp_like_count', 'orderby' =&gt; 'meta_value_num', ); </code></pre> <p>I have order by custom filed called <code>pp_like_count</code>. This works fine.</p> <p>But I need to display only <em>if <code>'pp_lang'</code> custom filed equals to 'english'</em>. How to modify this to add it?</p> <p>(Order by <code>pp_like_count</code> also should be there.)</p>
[ { "answer_id": 223278, "author": "Chetan", "author_id": 49618, "author_profile": "https://wordpress.stackexchange.com/users/49618", "pm_score": 0, "selected": false, "text": "<p>You can use meta query see below link it will help you.</p>\n\n<p><a href=\"https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/\" rel=\"nofollow\">How to order by meta field</a></p>\n" }, { "answer_id": 223281, "author": "Deepak jha", "author_id": 66318, "author_profile": "https://wordpress.stackexchange.com/users/66318", "pm_score": 2, "selected": true, "text": "<p>You can try this by using meta query to filter results and then adding orderby to order results. Below arguments should work</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; array('post', 'video'),\n 'meta_key' =&gt; 'pp_like_count',\n 'orderby' =&gt; 'meta_value_num',\n \"meta_query\" =&gt; array( \n array(\n \"key\" =&gt; \"pp_lang\",\n \"value\" =&gt; \"english\",\n \"type\" =&gt; \"CHAR\",\n \"compare\" =&gt; \"=\"\n ),\n ), \n);\n</code></pre>\n" } ]
2016/04/10
[ "https://wordpress.stackexchange.com/questions/223231", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56652/" ]
Note : This is not a duplicate question to [If value present, order posts by two consecutive custom fields](https://wordpress.stackexchange.com/questions/222148/if-value-present-order-posts-by-two-consecutive-custom-fields). After filtering a custom filed, I need to order by another custom filed. (The above link explains filtering by two custom fields. But I need to filter by a custom filed and then order by another custom filed. This is a my current wp query array. ``` $args = array( 'post_type' => array('post', 'video'), 'meta_key' => 'pp_like_count', 'orderby' => 'meta_value_num', ); ``` I have order by custom filed called `pp_like_count`. This works fine. But I need to display only *if `'pp_lang'` custom filed equals to 'english'*. How to modify this to add it? (Order by `pp_like_count` also should be there.)
You can try this by using meta query to filter results and then adding orderby to order results. Below arguments should work ``` $args = array( 'post_type' => array('post', 'video'), 'meta_key' => 'pp_like_count', 'orderby' => 'meta_value_num', "meta_query" => array( array( "key" => "pp_lang", "value" => "english", "type" => "CHAR", "compare" => "=" ), ), ); ```
223,235
<p>I'm a beginner in jQuery-Ajax so please bear with me. My Ajax response does not seem to load but my changes are being saved. but gives me this error on admin-ajax.php "call_user_func() expects parameter 1 to be a valid callback, function '_update_post_ter_count' not found or invalid function name" Here is my function, could you point what i'm doing wrong?</p> <pre><code>add_action( 'wp_ajax_nopriv_save_sort', 'ccmanz_save_reorder' ); add_action('wp_ajax_save_sort','ccmanz_save_reorder'); function ccmanz_save_reorder() { //checking //verify user intent check_ajax_referer( 'wp-job-order', 'security' ); // this comes from wp_localize_script() in hrm-jobs.php //capability check to ensure use caps if ( ! current_user_can( 'manage_options' ) ) { wp_die( __( 'You do not have permission to access this page.' ) ); } $order = explode( ',', $_POST['order'] ); $counter = 0; foreach ( $order as $item_id ) { $post = array( 'ID' =&gt; (int) $item_id, 'menu_order' =&gt; $counter, ); wp_update_post( $post ); $counter ++; } wp_send_json_success('POST SAVED'); } </code></pre> <p>My AJAX Call</p> <pre><code>jQuery(document).ready(function($) { sortList = $( 'ul#custom-type-list' ); //store var animation = $ ( '#loading-animation' ); var pageTitle = $ ( 'div h2'); sortList.sortable({ update: function ( event, ui) { animation.show(); $.ajax({ url: ajaxurl, // ajaxurl is defined by WordPress and points to /wp-admin/admin-ajax.php type: 'POST', async: true, cache: false, dataType: 'json', data:{ action: 'save_sort', // Tell WordPress how to handle this ajax request order: sortList.sortable( 'toArray' ).toString(), // Passes ID's of list items in 1,3,2 format security: WP_JOB_LISTING.security }, success: function( response ) { animation.hide(); $('div.updated').remove(); if( true === response.success ) { console.log(sortList.sortable( 'toArray' )); pageTitle.after( '&lt;div id="messsage" class="updated"&gt;&lt;p&gt;' + WP_JOB_LISTING.success + '&lt;/p&gt;&lt;/div&gt;' ); } else { $('div.error').remove(); pageTitle.after( '&lt;div id="messsage" class="error"&gt;&lt;p&gt;' + WP_JOB_LISTING.failure + '&lt;/div&gt;' ); } }, error: function ( error ) { $( 'div.error' ).remove(); animation.hide(); //pageTitle.after( '&lt;div id="messsage" class="error"&gt;&lt;p&gt;' + WP_JOB_LISTING.failure + '&lt;/div&gt;' ); } }); }//update }); //sortable });//jquery </code></pre>
[ { "answer_id": 223278, "author": "Chetan", "author_id": 49618, "author_profile": "https://wordpress.stackexchange.com/users/49618", "pm_score": 0, "selected": false, "text": "<p>You can use meta query see below link it will help you.</p>\n\n<p><a href=\"https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/\" rel=\"nofollow\">How to order by meta field</a></p>\n" }, { "answer_id": 223281, "author": "Deepak jha", "author_id": 66318, "author_profile": "https://wordpress.stackexchange.com/users/66318", "pm_score": 2, "selected": true, "text": "<p>You can try this by using meta query to filter results and then adding orderby to order results. Below arguments should work</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; array('post', 'video'),\n 'meta_key' =&gt; 'pp_like_count',\n 'orderby' =&gt; 'meta_value_num',\n \"meta_query\" =&gt; array( \n array(\n \"key\" =&gt; \"pp_lang\",\n \"value\" =&gt; \"english\",\n \"type\" =&gt; \"CHAR\",\n \"compare\" =&gt; \"=\"\n ),\n ), \n);\n</code></pre>\n" } ]
2016/04/10
[ "https://wordpress.stackexchange.com/questions/223235", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92111/" ]
I'm a beginner in jQuery-Ajax so please bear with me. My Ajax response does not seem to load but my changes are being saved. but gives me this error on admin-ajax.php "call\_user\_func() expects parameter 1 to be a valid callback, function '\_update\_post\_ter\_count' not found or invalid function name" Here is my function, could you point what i'm doing wrong? ``` add_action( 'wp_ajax_nopriv_save_sort', 'ccmanz_save_reorder' ); add_action('wp_ajax_save_sort','ccmanz_save_reorder'); function ccmanz_save_reorder() { //checking //verify user intent check_ajax_referer( 'wp-job-order', 'security' ); // this comes from wp_localize_script() in hrm-jobs.php //capability check to ensure use caps if ( ! current_user_can( 'manage_options' ) ) { wp_die( __( 'You do not have permission to access this page.' ) ); } $order = explode( ',', $_POST['order'] ); $counter = 0; foreach ( $order as $item_id ) { $post = array( 'ID' => (int) $item_id, 'menu_order' => $counter, ); wp_update_post( $post ); $counter ++; } wp_send_json_success('POST SAVED'); } ``` My AJAX Call ``` jQuery(document).ready(function($) { sortList = $( 'ul#custom-type-list' ); //store var animation = $ ( '#loading-animation' ); var pageTitle = $ ( 'div h2'); sortList.sortable({ update: function ( event, ui) { animation.show(); $.ajax({ url: ajaxurl, // ajaxurl is defined by WordPress and points to /wp-admin/admin-ajax.php type: 'POST', async: true, cache: false, dataType: 'json', data:{ action: 'save_sort', // Tell WordPress how to handle this ajax request order: sortList.sortable( 'toArray' ).toString(), // Passes ID's of list items in 1,3,2 format security: WP_JOB_LISTING.security }, success: function( response ) { animation.hide(); $('div.updated').remove(); if( true === response.success ) { console.log(sortList.sortable( 'toArray' )); pageTitle.after( '<div id="messsage" class="updated"><p>' + WP_JOB_LISTING.success + '</p></div>' ); } else { $('div.error').remove(); pageTitle.after( '<div id="messsage" class="error"><p>' + WP_JOB_LISTING.failure + '</div>' ); } }, error: function ( error ) { $( 'div.error' ).remove(); animation.hide(); //pageTitle.after( '<div id="messsage" class="error"><p>' + WP_JOB_LISTING.failure + '</div>' ); } }); }//update }); //sortable });//jquery ```
You can try this by using meta query to filter results and then adding orderby to order results. Below arguments should work ``` $args = array( 'post_type' => array('post', 'video'), 'meta_key' => 'pp_like_count', 'orderby' => 'meta_value_num', "meta_query" => array( array( "key" => "pp_lang", "value" => "english", "type" => "CHAR", "compare" => "=" ), ), ); ```
223,273
<p>I have a plugin and a custom post type class like this.</p> <p>I want to override one its function in my child theme. </p> <pre><code>class Inspiry_Property_Post_Type { /** * Register Property Post Type * @since 1.0.0 */ public function register_property_post_type() { $labels = array( 'name' =&gt; _x( 'Properties', 'Post Type General Name', 'inspiry-real-estate' ), 'singular_name' =&gt; _x( 'Property', 'Post Type Singular Name', 'inspiry-real-estate' ), 'menu_name' =&gt; __( 'Properties', 'inspiry-real-estate' ), 'name_admin_bar' =&gt; __( 'Property', 'inspiry-real-estate' ), 'parent_item_colon' =&gt; __( 'Parent Property:', 'inspiry-real-estate' ), 'all_items' =&gt; __( 'All Properties', 'inspiry-real-estate' ), 'add_new_item' =&gt; __( 'Add New Property', 'inspiry-real-estate' ), 'add_new' =&gt; __( 'Add New', 'inspiry-real-estate' ), 'new_item' =&gt; __( 'New Property', 'inspiry-real-estate' ), 'edit_item' =&gt; __( 'Edit Property', 'inspiry-real-estate' ), 'update_item' =&gt; __( 'Update Property', 'inspiry-real-estate' ), 'view_item' =&gt; __( 'View Property', 'inspiry-real-estate' ), 'search_items' =&gt; __( 'Search Property', 'inspiry-real-estate' ), 'not_found' =&gt; __( 'Not found', 'inspiry-real-estate' ), 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'inspiry-real-estate' ), ); $rewrite = array( 'slug' =&gt; apply_filters( 'inspiry_property_slug', __( 'property', 'inspiry-real-estate' ) ), 'with_front' =&gt; true, 'pages' =&gt; true, 'feeds' =&gt; true, ); $args = array( 'label' =&gt; __( 'property', 'inspiry-real-estate' ), 'description' =&gt; __( 'Real Estate Property', 'inspiry-real-estate' ), 'labels' =&gt; $labels, 'supports' =&gt; array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'revisions', 'page-attributes', 'comments' ), 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'menu_position' =&gt; 5, 'menu_icon' =&gt; 'dashicons-building', 'show_in_admin_bar' =&gt; true, 'show_in_nav_menus' =&gt; true, 'can_export' =&gt; true, 'has_archive' =&gt; true, 'exclude_from_search' =&gt; false, 'publicly_queryable' =&gt; true, 'rewrite' =&gt; $rewrite, 'capability_type' =&gt; 'post', ); register_post_type( 'property', $args ); } /** * Register Property Type Taxonomy * @since 1.0.0 */ public function register_property_type_taxonomy() { $labels = array( 'name' =&gt; _x( 'Property Type', 'Taxonomy General Name', 'inspiry-real-estate' ), 'singular_name' =&gt; _x( 'Property Type', 'Taxonomy Singular Name', 'inspiry-real-estate' ), 'menu_name' =&gt; __( 'Types', 'inspiry-real-estate' ), 'all_items' =&gt; __( 'All Property Types', 'inspiry-real-estate' ), 'parent_item' =&gt; __( 'Parent Property Type', 'inspiry-real-estate' ), 'parent_item_colon' =&gt; __( 'Parent Property Type:', 'inspiry-real-estate' ), 'new_item_name' =&gt; __( 'New Property Type Name', 'inspiry-real-estate' ), 'add_new_item' =&gt; __( 'Add New Property Type', 'inspiry-real-estate' ), 'edit_item' =&gt; __( 'Edit Property Type', 'inspiry-real-estate' ), 'update_item' =&gt; __( 'Update Property Type', 'inspiry-real-estate' ), 'view_item' =&gt; __( 'View Property Type', 'inspiry-real-estate' ), 'separate_items_with_commas' =&gt; __( 'Separate Property Types with commas', 'inspiry-real-estate' ), 'add_or_remove_items' =&gt; __( 'Add or remove Property Types', 'inspiry-real-estate' ), 'choose_from_most_used' =&gt; __( 'Choose from the most used', 'inspiry-real-estate' ), 'popular_items' =&gt; __( 'Popular Property Types', 'inspiry-real-estate' ), 'search_items' =&gt; __( 'Search Property Types', 'inspiry-real-estate' ), 'not_found' =&gt; __( 'Not Found', 'inspiry-real-estate' ), ); $rewrite = array( 'slug' =&gt; apply_filters( 'inspiry_property_type_slug', __( 'property-type', 'inspiry-real-estate' ) ), 'with_front' =&gt; true, 'hierarchical' =&gt; true, ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_tagcloud' =&gt; true, 'rewrite' =&gt; $rewrite, ); register_taxonomy( 'property-type', array( 'property' ), $args ); } /** * Register Property Status Taxonomy * @since 1.0.0 */ public function register_property_status_taxonomy() { $labels = array( 'name' =&gt; _x( 'Property Status', 'Taxonomy General Name', 'inspiry-real-estate' ), 'singular_name' =&gt; _x( 'Property Status', 'Taxonomy Singular Name', 'inspiry-real-estate' ), 'menu_name' =&gt; __( 'Statuses', 'inspiry-real-estate' ), 'all_items' =&gt; __( 'All Property Statuses', 'inspiry-real-estate' ), 'parent_item' =&gt; __( 'Parent Property Status', 'inspiry-real-estate' ), 'parent_item_colon' =&gt; __( 'Parent Property Status:', 'inspiry-real-estate' ), 'new_item_name' =&gt; __( 'New Property Status Name', 'inspiry-real-estate' ), 'add_new_item' =&gt; __( 'Add New Property Status', 'inspiry-real-estate' ), 'edit_item' =&gt; __( 'Edit Property Status', 'inspiry-real-estate' ), 'update_item' =&gt; __( 'Update Property Status', 'inspiry-real-estate' ), 'view_item' =&gt; __( 'View Property Status', 'inspiry-real-estate' ), 'separate_items_with_commas' =&gt; __( 'Separate Property Statuses with commas', 'inspiry-real-estate' ), 'add_or_remove_items' =&gt; __( 'Add or remove Property Statuses', 'inspiry-real-estate' ), 'choose_from_most_used' =&gt; __( 'Choose from the most used', 'inspiry-real-estate' ), 'popular_items' =&gt; __( 'Popular Property Statuses', 'inspiry-real-estate' ), 'search_items' =&gt; __( 'Search Property Statuses', 'inspiry-real-estate' ), 'not_found' =&gt; __( 'Not Found', 'inspiry-real-estate' ), ); $rewrite = array( 'slug' =&gt; apply_filters( 'inspiry_property_status_slug', __( 'property-status', 'inspiry-real-estate' ) ), 'with_front' =&gt; true, 'hierarchical' =&gt; true, ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_tagcloud' =&gt; true, 'rewrite' =&gt; $rewrite, ); register_taxonomy( 'property-status', array( 'property' ), $args ); } /** * Register Property City Taxonomy * @since 1.0.0 */ public function register_property_city_taxonomy() { $labels = array( 'name' =&gt; _x( 'Property City', 'Taxonomy General Name', 'inspiry-real-estate' ), 'singular_name' =&gt; _x( 'Property City', 'Taxonomy Singular Name', 'inspiry-real-estate' ), 'menu_name' =&gt; __( 'Locations', 'inspiry-real-estate' ), 'all_items' =&gt; __( 'All Property Cities', 'inspiry-real-estate' ), 'parent_item' =&gt; __( 'Parent Property City', 'inspiry-real-estate' ), 'parent_item_colon' =&gt; __( 'Parent Property City:', 'inspiry-real-estate' ), 'new_item_name' =&gt; __( 'New Property City Name', 'inspiry-real-estate' ), 'add_new_item' =&gt; __( 'Add New Property City', 'inspiry-real-estate' ), 'edit_item' =&gt; __( 'Edit Property City', 'inspiry-real-estate' ), 'update_item' =&gt; __( 'Update Property City', 'inspiry-real-estate' ), 'view_item' =&gt; __( 'View Property City', 'inspiry-real-estate' ), 'separate_items_with_commas' =&gt; __( 'Separate Property Cities with commas', 'inspiry-real-estate' ), 'add_or_remove_items' =&gt; __( 'Add or remove Property Cities', 'inspiry-real-estate' ), 'choose_from_most_used' =&gt; __( 'Choose from the most used', 'inspiry-real-estate' ), 'popular_items' =&gt; __( 'Popular Property Cities', 'inspiry-real-estate' ), 'search_items' =&gt; __( 'Search Property Cities', 'inspiry-real-estate' ), 'not_found' =&gt; __( 'Not Found', 'inspiry-real-estate' ), ); $rewrite = array( 'slug' =&gt; apply_filters( 'inspiry_property_city_slug', __( 'property-city', 'inspiry-real-estate' ) ), 'with_front' =&gt; true, 'hierarchical' =&gt; true, ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_tagcloud' =&gt; true, 'rewrite' =&gt; $rewrite, ); register_taxonomy( 'property-city', array( 'property' ), $args ); } /** * Register custom columns * * @param array $defaults * @since 1.0.0 * @return array $defaults */ public function register_custom_column_titles ( $defaults ) { $new_columns = array( "thumb" =&gt; __( 'Photo', 'inspiry-real-estate' ), "id" =&gt; __( 'Custom ID', 'inspiry-real-estate' ), "price" =&gt; __( 'Price', 'inspiry-real-estate'), ); $last_columns = array(); if ( count( $defaults ) &gt; 5 ) { unset( $defaults['author'] ); $last_columns = array_splice( $defaults, 2, 4 ); // Simplify column titles $last_columns[ 'taxonomy-property-type' ] = __( 'Type', 'inspiry-real-estate' ); $last_columns[ 'taxonomy-property-status' ] = __( 'Status', 'inspiry-real-estate' ); $last_columns[ 'taxonomy-property-city' ] = __( 'Location', 'inspiry-real-estate' ); } $defaults = array_merge( $defaults, $new_columns ); $defaults = array_merge( $defaults, $last_columns ); return $defaults; } /** * Display custom column for properties * * @access public * @param string $column_name * @since 1.0.0 * @return void */ public function display_custom_column ( $column_name ) { global $post; switch ( $column_name ) { case 'thumb': if ( has_post_thumbnail ( $post-&gt;ID ) ) { ?&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" target="_blank"&gt;&lt;?php the_post_thumbnail( array( 130, 130 ) );?&gt;&lt;/a&gt;&lt;?php } else { _e ( 'No Image', 'inspiry-real-estate' ); } break; case 'id': $property_id = get_post_meta ( $post-&gt;ID, 'REAL_HOMES_property_id', true ); if( ! empty ( $property_id ) ) { echo $property_id; } else { _e ( 'NA', 'inspiry-real-estate' ); } break; case 'price': $property_price = get_post_meta ( $post-&gt;ID, 'REAL_HOMES_property_price', true ); if ( !empty ( $property_price ) ) { $price_amount = doubleval( $property_price ); $price_postfix = get_post_meta ( $post-&gt;ID, 'REAL_HOMES_property_price_postfix', true ); echo Inspiry_Property::format_price( $price_amount, $price_postfix ); } else { _e ( 'NA', 'inspiry-real-estate' ); } break; default: break; } } /** * Register meta boxes related to property post type * * @param array $meta_boxes * @since 1.0.0 * @return array $meta_boxes */ public function register_meta_boxes ( $meta_boxes ){ $prefix = 'REAL_HOMES_'; // Agents $agents_array = array( -1 =&gt; __( 'None', 'inspiry-real-estate' ) ); $agents_posts = get_posts( array ( 'post_type' =&gt; 'agent', 'posts_per_page' =&gt; -1, 'suppress_filters' =&gt; 0, ) ); if ( ! empty ( $agents_posts ) ) { foreach ( $agents_posts as $agent_post ) { $agents_array[ $agent_post-&gt;ID ] = $agent_post-&gt;post_title; } } // Property Details Meta Box $default_desc = __( 'Consult theme documentation for required image size.', 'inspiry-real-estate' ); $gallery_images_desc = apply_filters( 'inspiry_gallery_description', $default_desc ); $video_image_desc = apply_filters( 'inspiry_video_description', $default_desc ); $slider_image_desc = apply_filters( 'inspiry_slider_description', $default_desc ); $meta_boxes[] = array( 'id' =&gt; 'property-meta-box', 'title' =&gt; __('Property', 'inspiry-real-estate'), 'pages' =&gt; array('property'), 'tabs' =&gt; array( 'details' =&gt; array( 'label' =&gt; __('Basic Information', 'inspiry-real-estate'), 'icon' =&gt; 'dashicons-admin-home', ), 'gallery' =&gt; array( 'label' =&gt; __('Gallery Images', 'inspiry-real-estate'), 'icon' =&gt; 'dashicons-format-gallery', ), 'video' =&gt; array( 'label' =&gt; __('Property Video', 'inspiry-real-estate'), 'icon' =&gt; 'dashicons-format-video', ), 'agent' =&gt; array( 'label' =&gt; __('Agent Information', 'inspiry-real-estate'), 'icon' =&gt; 'dashicons-businessman', ), 'misc' =&gt; array( 'label' =&gt; __('Misc', 'inspiry-real-estate'), 'icon' =&gt; 'dashicons-lightbulb', ), 'home-slider' =&gt; array( 'label' =&gt; __('Homepage Slider', 'inspiry-real-estate'), 'icon' =&gt; 'dashicons-images-alt', ), 'banner' =&gt; array( 'label' =&gt; __('Top Banner', 'inspiry-real-estate'), 'icon' =&gt; 'dashicons-format-image', ), ), 'tab_style' =&gt; 'left', 'fields' =&gt; array( // Details array( 'id' =&gt; "{$prefix}property_price", 'name' =&gt; __('Sale or Rent Price ( Only digits )', 'inspiry-real-estate'), 'desc' =&gt; __('Example Value: 435000', 'inspiry-real-estate'), 'type' =&gt; 'text', 'std' =&gt; "", 'columns' =&gt; 6, 'tab' =&gt; 'details', ), array( 'id' =&gt; "{$prefix}property_price_postfix", 'name' =&gt; __('Price Postfix', 'inspiry-real-estate'), 'desc' =&gt; __('Example Value: Per Month', 'inspiry-real-estate'), 'type' =&gt; 'text', 'std' =&gt; "", 'columns' =&gt; 6, 'tab' =&gt; 'details', ), array( 'id' =&gt; "{$prefix}property_size", 'name' =&gt; __('Area Size ( Only digits )', 'inspiry-real-estate'), 'desc' =&gt; __('Example Value: 2500', 'inspiry-real-estate'), 'type' =&gt; 'text', 'std' =&gt; "", 'columns' =&gt; 6, 'tab' =&gt; 'details', ), array( 'id' =&gt; "{$prefix}property_size_postfix", 'name' =&gt; __('Size Postfix', 'inspiry-real-estate'), 'desc' =&gt; __('Example Value: Sq Ft', 'inspiry-real-estate'), 'type' =&gt; 'text', 'std' =&gt; "", 'columns' =&gt; 6, 'tab' =&gt; 'details', ), array( 'id' =&gt; "{$prefix}property_bedrooms", 'name' =&gt; __('Bedrooms', 'inspiry-real-estate'), 'desc' =&gt; __('Example Value: 4', 'inspiry-real-estate'), 'type' =&gt; 'text', 'std' =&gt; "", 'columns' =&gt; 6, 'tab' =&gt; 'details', ), array( 'id' =&gt; "{$prefix}property_bathrooms", 'name' =&gt; __('Bathrooms', 'inspiry-real-estate'), 'desc' =&gt; __('Example Value: 2', 'inspiry-real-estate'), 'type' =&gt; 'text', 'std' =&gt; "", 'columns' =&gt; 6, 'tab' =&gt; 'details', ), array( 'id' =&gt; "{$prefix}property_garage", 'name' =&gt; __('Garages', 'inspiry-real-estate'), 'desc' =&gt; __('Example Value: 1', 'inspiry-real-estate'), 'type' =&gt; 'text', 'std' =&gt; "", 'columns' =&gt; 6, 'tab' =&gt; 'details', ), array( 'id' =&gt; "{$prefix}property_id", 'name' =&gt; __('Property ID', 'inspiry-real-estate'), 'desc' =&gt; __('It will help you search a property directly.', 'inspiry-real-estate'), 'type' =&gt; 'text', 'std' =&gt; "", 'columns' =&gt; 6, 'tab' =&gt; 'details', ), // Map array( 'type' =&gt; 'divider', 'columns' =&gt; 12, 'id' =&gt; 'google_map_divider', // Not used, but needed 'tab' =&gt; 'details', ), array( 'id' =&gt; "{$prefix}property_address", 'name' =&gt; __('Property Address', 'inspiry-real-estate'), 'desc' =&gt; __('Leaving it empty will hide the google map on property detail page.', 'inspiry-real-estate'), 'type' =&gt; 'text', // 'std' =&gt; 'Miami, FL, USA', 'columns' =&gt; 12, 'tab' =&gt; 'details', ), array( 'id' =&gt; "{$prefix}property_location", 'name' =&gt; __('Property Location at Google Map*', 'inspiry-real-estate'), 'desc' =&gt; __('Drag the google map marker to point your property location. You can also use the address field above to search for your property.', 'inspiry-real-estate'), 'type' =&gt; 'map', 'std' =&gt; '25.761680,-80.191790,14', // 'latitude,longitude[,zoom]' (zoom is optional) 'style' =&gt; 'width: 95%; height: 400px', 'address_field' =&gt; "{$prefix}property_address", 'columns' =&gt; 12, 'tab' =&gt; 'details', ), array( 'name' =&gt; __('Property Gallery Images', 'inspiry-real-estate'), 'id' =&gt; "{$prefix}property_images", 'desc' =&gt; $gallery_images_desc, 'type' =&gt; 'image_advanced', 'max_file_uploads' =&gt; 48, 'columns' =&gt; 12, 'tab' =&gt; 'gallery', ), // Property Video array( 'id' =&gt; "{$prefix}tour_video_url", 'name' =&gt; __('Virtual Tour Video URL', 'inspiry-real-estate'), 'desc' =&gt; __('Provide virtual tour video URL. YouTube, Vimeo, SWF File and MOV File are supported', 'inspiry-real-estate'), 'type' =&gt; 'text', 'columns' =&gt; 12, 'tab' =&gt; 'video', ), array( 'name' =&gt; __('Virtual Tour Video Image', 'inspiry-real-estate'), 'id' =&gt; "{$prefix}tour_video_image", 'desc' =&gt; $video_image_desc, 'type' =&gt; 'image_advanced', 'max_file_uploads' =&gt; 1, 'columns' =&gt; 12, 'tab' =&gt; 'video', ), // Agents array( 'name' =&gt; __('What to display in agent information box ?', 'inspiry-real-estate'), 'id' =&gt; "{$prefix}agent_display_option", 'type' =&gt; 'radio', 'std' =&gt; 'none', 'options' =&gt; array( 'my_profile_info' =&gt; __('Author information.', 'inspiry-real-estate'), 'agent_info' =&gt; __('Agent Information. ( Select the agent below )', 'inspiry-real-estate'), 'none' =&gt; __('None. ( Hide information box )', 'inspiry-real-estate'), ), 'columns' =&gt; 12, 'tab' =&gt; 'agent', ), array( 'name' =&gt; __('Agent', 'inspiry-real-estate'), 'id' =&gt; "{$prefix}agents", 'type' =&gt; 'select', 'options' =&gt; $agents_array, 'columns' =&gt; 12, 'tab' =&gt; 'agent', ), // Misc array( 'name' =&gt; __('Mark this property as featured ?', 'inspiry-real-estate'), 'id' =&gt; "{$prefix}featured", 'type' =&gt; 'radio', 'std' =&gt; 0, 'options' =&gt; array( 1 =&gt; __('Yes ', 'inspiry-real-estate'), 0 =&gt; __('No', 'inspiry-real-estate') ), 'columns' =&gt; 12, 'tab' =&gt; 'misc', ), array( 'id' =&gt; "{$prefix}attachments", 'name' =&gt; __('Attachments', 'inspiry-real-estate'), 'desc' =&gt; __('You can attach PDF files, Map images OR other documents to provide further details related to property.', 'inspiry-real-estate'), 'type' =&gt; 'file_advanced', 'mime_type' =&gt; '', 'columns' =&gt; 12, 'tab' =&gt; 'misc', ), array( 'id' =&gt; "{$prefix}property_private_note", 'name' =&gt; __('Private Note', 'inspiry-real-estate'), 'desc' =&gt; __('In this textarea, You can write your private note about this property. This field will not be displayed anywhere else.', 'inspiry-real-estate'), 'type' =&gt; 'textarea', 'std' =&gt; "", 'columns' =&gt; 12, 'tab' =&gt; 'misc', ), // Homepage Slider array( 'name' =&gt; __('Do you want to add this property in Homepage Slider ?', 'inspiry-real-estate'), 'desc' =&gt; __('If Yes, Then you need to provide a slider image below.', 'inspiry-real-estate'), 'id' =&gt; "{$prefix}add_in_slider", 'type' =&gt; 'radio', 'std' =&gt; 'no', 'options' =&gt; array( 'yes' =&gt; __('Yes ', 'inspiry-real-estate'), 'no' =&gt; __('No', 'inspiry-real-estate') ), 'columns' =&gt; 12, 'tab' =&gt; 'home-slider', ), array( 'name' =&gt; __('Slider Image', 'inspiry-real-estate'), 'id' =&gt; "{$prefix}slider_image", 'desc' =&gt; $slider_image_desc, 'type' =&gt; 'image_advanced', 'max_file_uploads' =&gt; 1, 'columns' =&gt; 12, 'tab' =&gt; 'home-slider', ), // Top Banner array( 'name' =&gt; __('Top Banner Image', 'inspiry-real-estate'), 'id' =&gt; "{$prefix}page_banner_image", 'desc' =&gt; __('Upload the banner image, If you want to change it for this property. Otherwise default banner image uploaded from theme options will be displayed. Image should have minimum width of 2000px and minimum height of 230px.', 'inspiry-real-estate'), 'type' =&gt; 'image_advanced', 'max_file_uploads' =&gt; 1, 'columns' =&gt; 12, 'tab' =&gt; 'banner', ) ) ); // apply a filter before returning meta boxes $meta_boxes = apply_filters( 'property_meta_boxes', $meta_boxes ); return $meta_boxes; } </code></pre> <p>}</p> <p>How can I override the <strong>register_meta_boxes</strong> function? I want to remove some of the meta boxes defined in this parent class. Thanks!</p>
[ { "answer_id": 223274, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 0, "selected": false, "text": "<p>Depending on how the main class is set up, you can create a child class of the parent class. Something like:</p>\n\n<pre><code>class Custom_Post_Type_Child extends Custom_Post_Type {\n{\n public function doSomething ( $var ){\n return $var;\n }\n}\n</code></pre>\n" }, { "answer_id": 223321, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>In general you can not override functions or methods in PHP. Code can be written to support such things, but it needs to be planned in advance, and your snippet is not big enough to be able to decide if it is possible or not in your case.</p>\n\n<p>The good thing, is that you do not need to override any function at all as the output of that function is filterable by using the <code>'property_meta_boxes'</code> filter, so just do something like</p>\n\n<pre><code>add_filter('property_meta_boxes','wpse223273_meta_boxes');\n\nfunction wpse223273_meta_boxes($metaboxes) {\n $my_meta = array(.... your meta box settings....);\n return $my_meta;\n}\n</code></pre>\n" } ]
2016/04/10
[ "https://wordpress.stackexchange.com/questions/223273", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90826/" ]
I have a plugin and a custom post type class like this. I want to override one its function in my child theme. ``` class Inspiry_Property_Post_Type { /** * Register Property Post Type * @since 1.0.0 */ public function register_property_post_type() { $labels = array( 'name' => _x( 'Properties', 'Post Type General Name', 'inspiry-real-estate' ), 'singular_name' => _x( 'Property', 'Post Type Singular Name', 'inspiry-real-estate' ), 'menu_name' => __( 'Properties', 'inspiry-real-estate' ), 'name_admin_bar' => __( 'Property', 'inspiry-real-estate' ), 'parent_item_colon' => __( 'Parent Property:', 'inspiry-real-estate' ), 'all_items' => __( 'All Properties', 'inspiry-real-estate' ), 'add_new_item' => __( 'Add New Property', 'inspiry-real-estate' ), 'add_new' => __( 'Add New', 'inspiry-real-estate' ), 'new_item' => __( 'New Property', 'inspiry-real-estate' ), 'edit_item' => __( 'Edit Property', 'inspiry-real-estate' ), 'update_item' => __( 'Update Property', 'inspiry-real-estate' ), 'view_item' => __( 'View Property', 'inspiry-real-estate' ), 'search_items' => __( 'Search Property', 'inspiry-real-estate' ), 'not_found' => __( 'Not found', 'inspiry-real-estate' ), 'not_found_in_trash' => __( 'Not found in Trash', 'inspiry-real-estate' ), ); $rewrite = array( 'slug' => apply_filters( 'inspiry_property_slug', __( 'property', 'inspiry-real-estate' ) ), 'with_front' => true, 'pages' => true, 'feeds' => true, ); $args = array( 'label' => __( 'property', 'inspiry-real-estate' ), 'description' => __( 'Real Estate Property', 'inspiry-real-estate' ), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'revisions', 'page-attributes', 'comments' ), 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'menu_icon' => 'dashicons-building', 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'rewrite' => $rewrite, 'capability_type' => 'post', ); register_post_type( 'property', $args ); } /** * Register Property Type Taxonomy * @since 1.0.0 */ public function register_property_type_taxonomy() { $labels = array( 'name' => _x( 'Property Type', 'Taxonomy General Name', 'inspiry-real-estate' ), 'singular_name' => _x( 'Property Type', 'Taxonomy Singular Name', 'inspiry-real-estate' ), 'menu_name' => __( 'Types', 'inspiry-real-estate' ), 'all_items' => __( 'All Property Types', 'inspiry-real-estate' ), 'parent_item' => __( 'Parent Property Type', 'inspiry-real-estate' ), 'parent_item_colon' => __( 'Parent Property Type:', 'inspiry-real-estate' ), 'new_item_name' => __( 'New Property Type Name', 'inspiry-real-estate' ), 'add_new_item' => __( 'Add New Property Type', 'inspiry-real-estate' ), 'edit_item' => __( 'Edit Property Type', 'inspiry-real-estate' ), 'update_item' => __( 'Update Property Type', 'inspiry-real-estate' ), 'view_item' => __( 'View Property Type', 'inspiry-real-estate' ), 'separate_items_with_commas' => __( 'Separate Property Types with commas', 'inspiry-real-estate' ), 'add_or_remove_items' => __( 'Add or remove Property Types', 'inspiry-real-estate' ), 'choose_from_most_used' => __( 'Choose from the most used', 'inspiry-real-estate' ), 'popular_items' => __( 'Popular Property Types', 'inspiry-real-estate' ), 'search_items' => __( 'Search Property Types', 'inspiry-real-estate' ), 'not_found' => __( 'Not Found', 'inspiry-real-estate' ), ); $rewrite = array( 'slug' => apply_filters( 'inspiry_property_type_slug', __( 'property-type', 'inspiry-real-estate' ) ), 'with_front' => true, 'hierarchical' => true, ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, 'rewrite' => $rewrite, ); register_taxonomy( 'property-type', array( 'property' ), $args ); } /** * Register Property Status Taxonomy * @since 1.0.0 */ public function register_property_status_taxonomy() { $labels = array( 'name' => _x( 'Property Status', 'Taxonomy General Name', 'inspiry-real-estate' ), 'singular_name' => _x( 'Property Status', 'Taxonomy Singular Name', 'inspiry-real-estate' ), 'menu_name' => __( 'Statuses', 'inspiry-real-estate' ), 'all_items' => __( 'All Property Statuses', 'inspiry-real-estate' ), 'parent_item' => __( 'Parent Property Status', 'inspiry-real-estate' ), 'parent_item_colon' => __( 'Parent Property Status:', 'inspiry-real-estate' ), 'new_item_name' => __( 'New Property Status Name', 'inspiry-real-estate' ), 'add_new_item' => __( 'Add New Property Status', 'inspiry-real-estate' ), 'edit_item' => __( 'Edit Property Status', 'inspiry-real-estate' ), 'update_item' => __( 'Update Property Status', 'inspiry-real-estate' ), 'view_item' => __( 'View Property Status', 'inspiry-real-estate' ), 'separate_items_with_commas' => __( 'Separate Property Statuses with commas', 'inspiry-real-estate' ), 'add_or_remove_items' => __( 'Add or remove Property Statuses', 'inspiry-real-estate' ), 'choose_from_most_used' => __( 'Choose from the most used', 'inspiry-real-estate' ), 'popular_items' => __( 'Popular Property Statuses', 'inspiry-real-estate' ), 'search_items' => __( 'Search Property Statuses', 'inspiry-real-estate' ), 'not_found' => __( 'Not Found', 'inspiry-real-estate' ), ); $rewrite = array( 'slug' => apply_filters( 'inspiry_property_status_slug', __( 'property-status', 'inspiry-real-estate' ) ), 'with_front' => true, 'hierarchical' => true, ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, 'rewrite' => $rewrite, ); register_taxonomy( 'property-status', array( 'property' ), $args ); } /** * Register Property City Taxonomy * @since 1.0.0 */ public function register_property_city_taxonomy() { $labels = array( 'name' => _x( 'Property City', 'Taxonomy General Name', 'inspiry-real-estate' ), 'singular_name' => _x( 'Property City', 'Taxonomy Singular Name', 'inspiry-real-estate' ), 'menu_name' => __( 'Locations', 'inspiry-real-estate' ), 'all_items' => __( 'All Property Cities', 'inspiry-real-estate' ), 'parent_item' => __( 'Parent Property City', 'inspiry-real-estate' ), 'parent_item_colon' => __( 'Parent Property City:', 'inspiry-real-estate' ), 'new_item_name' => __( 'New Property City Name', 'inspiry-real-estate' ), 'add_new_item' => __( 'Add New Property City', 'inspiry-real-estate' ), 'edit_item' => __( 'Edit Property City', 'inspiry-real-estate' ), 'update_item' => __( 'Update Property City', 'inspiry-real-estate' ), 'view_item' => __( 'View Property City', 'inspiry-real-estate' ), 'separate_items_with_commas' => __( 'Separate Property Cities with commas', 'inspiry-real-estate' ), 'add_or_remove_items' => __( 'Add or remove Property Cities', 'inspiry-real-estate' ), 'choose_from_most_used' => __( 'Choose from the most used', 'inspiry-real-estate' ), 'popular_items' => __( 'Popular Property Cities', 'inspiry-real-estate' ), 'search_items' => __( 'Search Property Cities', 'inspiry-real-estate' ), 'not_found' => __( 'Not Found', 'inspiry-real-estate' ), ); $rewrite = array( 'slug' => apply_filters( 'inspiry_property_city_slug', __( 'property-city', 'inspiry-real-estate' ) ), 'with_front' => true, 'hierarchical' => true, ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, 'rewrite' => $rewrite, ); register_taxonomy( 'property-city', array( 'property' ), $args ); } /** * Register custom columns * * @param array $defaults * @since 1.0.0 * @return array $defaults */ public function register_custom_column_titles ( $defaults ) { $new_columns = array( "thumb" => __( 'Photo', 'inspiry-real-estate' ), "id" => __( 'Custom ID', 'inspiry-real-estate' ), "price" => __( 'Price', 'inspiry-real-estate'), ); $last_columns = array(); if ( count( $defaults ) > 5 ) { unset( $defaults['author'] ); $last_columns = array_splice( $defaults, 2, 4 ); // Simplify column titles $last_columns[ 'taxonomy-property-type' ] = __( 'Type', 'inspiry-real-estate' ); $last_columns[ 'taxonomy-property-status' ] = __( 'Status', 'inspiry-real-estate' ); $last_columns[ 'taxonomy-property-city' ] = __( 'Location', 'inspiry-real-estate' ); } $defaults = array_merge( $defaults, $new_columns ); $defaults = array_merge( $defaults, $last_columns ); return $defaults; } /** * Display custom column for properties * * @access public * @param string $column_name * @since 1.0.0 * @return void */ public function display_custom_column ( $column_name ) { global $post; switch ( $column_name ) { case 'thumb': if ( has_post_thumbnail ( $post->ID ) ) { ?><a href="<?php the_permalink(); ?>" target="_blank"><?php the_post_thumbnail( array( 130, 130 ) );?></a><?php } else { _e ( 'No Image', 'inspiry-real-estate' ); } break; case 'id': $property_id = get_post_meta ( $post->ID, 'REAL_HOMES_property_id', true ); if( ! empty ( $property_id ) ) { echo $property_id; } else { _e ( 'NA', 'inspiry-real-estate' ); } break; case 'price': $property_price = get_post_meta ( $post->ID, 'REAL_HOMES_property_price', true ); if ( !empty ( $property_price ) ) { $price_amount = doubleval( $property_price ); $price_postfix = get_post_meta ( $post->ID, 'REAL_HOMES_property_price_postfix', true ); echo Inspiry_Property::format_price( $price_amount, $price_postfix ); } else { _e ( 'NA', 'inspiry-real-estate' ); } break; default: break; } } /** * Register meta boxes related to property post type * * @param array $meta_boxes * @since 1.0.0 * @return array $meta_boxes */ public function register_meta_boxes ( $meta_boxes ){ $prefix = 'REAL_HOMES_'; // Agents $agents_array = array( -1 => __( 'None', 'inspiry-real-estate' ) ); $agents_posts = get_posts( array ( 'post_type' => 'agent', 'posts_per_page' => -1, 'suppress_filters' => 0, ) ); if ( ! empty ( $agents_posts ) ) { foreach ( $agents_posts as $agent_post ) { $agents_array[ $agent_post->ID ] = $agent_post->post_title; } } // Property Details Meta Box $default_desc = __( 'Consult theme documentation for required image size.', 'inspiry-real-estate' ); $gallery_images_desc = apply_filters( 'inspiry_gallery_description', $default_desc ); $video_image_desc = apply_filters( 'inspiry_video_description', $default_desc ); $slider_image_desc = apply_filters( 'inspiry_slider_description', $default_desc ); $meta_boxes[] = array( 'id' => 'property-meta-box', 'title' => __('Property', 'inspiry-real-estate'), 'pages' => array('property'), 'tabs' => array( 'details' => array( 'label' => __('Basic Information', 'inspiry-real-estate'), 'icon' => 'dashicons-admin-home', ), 'gallery' => array( 'label' => __('Gallery Images', 'inspiry-real-estate'), 'icon' => 'dashicons-format-gallery', ), 'video' => array( 'label' => __('Property Video', 'inspiry-real-estate'), 'icon' => 'dashicons-format-video', ), 'agent' => array( 'label' => __('Agent Information', 'inspiry-real-estate'), 'icon' => 'dashicons-businessman', ), 'misc' => array( 'label' => __('Misc', 'inspiry-real-estate'), 'icon' => 'dashicons-lightbulb', ), 'home-slider' => array( 'label' => __('Homepage Slider', 'inspiry-real-estate'), 'icon' => 'dashicons-images-alt', ), 'banner' => array( 'label' => __('Top Banner', 'inspiry-real-estate'), 'icon' => 'dashicons-format-image', ), ), 'tab_style' => 'left', 'fields' => array( // Details array( 'id' => "{$prefix}property_price", 'name' => __('Sale or Rent Price ( Only digits )', 'inspiry-real-estate'), 'desc' => __('Example Value: 435000', 'inspiry-real-estate'), 'type' => 'text', 'std' => "", 'columns' => 6, 'tab' => 'details', ), array( 'id' => "{$prefix}property_price_postfix", 'name' => __('Price Postfix', 'inspiry-real-estate'), 'desc' => __('Example Value: Per Month', 'inspiry-real-estate'), 'type' => 'text', 'std' => "", 'columns' => 6, 'tab' => 'details', ), array( 'id' => "{$prefix}property_size", 'name' => __('Area Size ( Only digits )', 'inspiry-real-estate'), 'desc' => __('Example Value: 2500', 'inspiry-real-estate'), 'type' => 'text', 'std' => "", 'columns' => 6, 'tab' => 'details', ), array( 'id' => "{$prefix}property_size_postfix", 'name' => __('Size Postfix', 'inspiry-real-estate'), 'desc' => __('Example Value: Sq Ft', 'inspiry-real-estate'), 'type' => 'text', 'std' => "", 'columns' => 6, 'tab' => 'details', ), array( 'id' => "{$prefix}property_bedrooms", 'name' => __('Bedrooms', 'inspiry-real-estate'), 'desc' => __('Example Value: 4', 'inspiry-real-estate'), 'type' => 'text', 'std' => "", 'columns' => 6, 'tab' => 'details', ), array( 'id' => "{$prefix}property_bathrooms", 'name' => __('Bathrooms', 'inspiry-real-estate'), 'desc' => __('Example Value: 2', 'inspiry-real-estate'), 'type' => 'text', 'std' => "", 'columns' => 6, 'tab' => 'details', ), array( 'id' => "{$prefix}property_garage", 'name' => __('Garages', 'inspiry-real-estate'), 'desc' => __('Example Value: 1', 'inspiry-real-estate'), 'type' => 'text', 'std' => "", 'columns' => 6, 'tab' => 'details', ), array( 'id' => "{$prefix}property_id", 'name' => __('Property ID', 'inspiry-real-estate'), 'desc' => __('It will help you search a property directly.', 'inspiry-real-estate'), 'type' => 'text', 'std' => "", 'columns' => 6, 'tab' => 'details', ), // Map array( 'type' => 'divider', 'columns' => 12, 'id' => 'google_map_divider', // Not used, but needed 'tab' => 'details', ), array( 'id' => "{$prefix}property_address", 'name' => __('Property Address', 'inspiry-real-estate'), 'desc' => __('Leaving it empty will hide the google map on property detail page.', 'inspiry-real-estate'), 'type' => 'text', // 'std' => 'Miami, FL, USA', 'columns' => 12, 'tab' => 'details', ), array( 'id' => "{$prefix}property_location", 'name' => __('Property Location at Google Map*', 'inspiry-real-estate'), 'desc' => __('Drag the google map marker to point your property location. You can also use the address field above to search for your property.', 'inspiry-real-estate'), 'type' => 'map', 'std' => '25.761680,-80.191790,14', // 'latitude,longitude[,zoom]' (zoom is optional) 'style' => 'width: 95%; height: 400px', 'address_field' => "{$prefix}property_address", 'columns' => 12, 'tab' => 'details', ), array( 'name' => __('Property Gallery Images', 'inspiry-real-estate'), 'id' => "{$prefix}property_images", 'desc' => $gallery_images_desc, 'type' => 'image_advanced', 'max_file_uploads' => 48, 'columns' => 12, 'tab' => 'gallery', ), // Property Video array( 'id' => "{$prefix}tour_video_url", 'name' => __('Virtual Tour Video URL', 'inspiry-real-estate'), 'desc' => __('Provide virtual tour video URL. YouTube, Vimeo, SWF File and MOV File are supported', 'inspiry-real-estate'), 'type' => 'text', 'columns' => 12, 'tab' => 'video', ), array( 'name' => __('Virtual Tour Video Image', 'inspiry-real-estate'), 'id' => "{$prefix}tour_video_image", 'desc' => $video_image_desc, 'type' => 'image_advanced', 'max_file_uploads' => 1, 'columns' => 12, 'tab' => 'video', ), // Agents array( 'name' => __('What to display in agent information box ?', 'inspiry-real-estate'), 'id' => "{$prefix}agent_display_option", 'type' => 'radio', 'std' => 'none', 'options' => array( 'my_profile_info' => __('Author information.', 'inspiry-real-estate'), 'agent_info' => __('Agent Information. ( Select the agent below )', 'inspiry-real-estate'), 'none' => __('None. ( Hide information box )', 'inspiry-real-estate'), ), 'columns' => 12, 'tab' => 'agent', ), array( 'name' => __('Agent', 'inspiry-real-estate'), 'id' => "{$prefix}agents", 'type' => 'select', 'options' => $agents_array, 'columns' => 12, 'tab' => 'agent', ), // Misc array( 'name' => __('Mark this property as featured ?', 'inspiry-real-estate'), 'id' => "{$prefix}featured", 'type' => 'radio', 'std' => 0, 'options' => array( 1 => __('Yes ', 'inspiry-real-estate'), 0 => __('No', 'inspiry-real-estate') ), 'columns' => 12, 'tab' => 'misc', ), array( 'id' => "{$prefix}attachments", 'name' => __('Attachments', 'inspiry-real-estate'), 'desc' => __('You can attach PDF files, Map images OR other documents to provide further details related to property.', 'inspiry-real-estate'), 'type' => 'file_advanced', 'mime_type' => '', 'columns' => 12, 'tab' => 'misc', ), array( 'id' => "{$prefix}property_private_note", 'name' => __('Private Note', 'inspiry-real-estate'), 'desc' => __('In this textarea, You can write your private note about this property. This field will not be displayed anywhere else.', 'inspiry-real-estate'), 'type' => 'textarea', 'std' => "", 'columns' => 12, 'tab' => 'misc', ), // Homepage Slider array( 'name' => __('Do you want to add this property in Homepage Slider ?', 'inspiry-real-estate'), 'desc' => __('If Yes, Then you need to provide a slider image below.', 'inspiry-real-estate'), 'id' => "{$prefix}add_in_slider", 'type' => 'radio', 'std' => 'no', 'options' => array( 'yes' => __('Yes ', 'inspiry-real-estate'), 'no' => __('No', 'inspiry-real-estate') ), 'columns' => 12, 'tab' => 'home-slider', ), array( 'name' => __('Slider Image', 'inspiry-real-estate'), 'id' => "{$prefix}slider_image", 'desc' => $slider_image_desc, 'type' => 'image_advanced', 'max_file_uploads' => 1, 'columns' => 12, 'tab' => 'home-slider', ), // Top Banner array( 'name' => __('Top Banner Image', 'inspiry-real-estate'), 'id' => "{$prefix}page_banner_image", 'desc' => __('Upload the banner image, If you want to change it for this property. Otherwise default banner image uploaded from theme options will be displayed. Image should have minimum width of 2000px and minimum height of 230px.', 'inspiry-real-estate'), 'type' => 'image_advanced', 'max_file_uploads' => 1, 'columns' => 12, 'tab' => 'banner', ) ) ); // apply a filter before returning meta boxes $meta_boxes = apply_filters( 'property_meta_boxes', $meta_boxes ); return $meta_boxes; } ``` } How can I override the **register\_meta\_boxes** function? I want to remove some of the meta boxes defined in this parent class. Thanks!
In general you can not override functions or methods in PHP. Code can be written to support such things, but it needs to be planned in advance, and your snippet is not big enough to be able to decide if it is possible or not in your case. The good thing, is that you do not need to override any function at all as the output of that function is filterable by using the `'property_meta_boxes'` filter, so just do something like ``` add_filter('property_meta_boxes','wpse223273_meta_boxes'); function wpse223273_meta_boxes($metaboxes) { $my_meta = array(.... your meta box settings....); return $my_meta; } ```
223,325
<p>After switching to a different wordpress theme, Google started adding a sitename to ALL page titles in the search results. </p> <p>E.g.:</p> <blockquote> <p>"Page title - Sitename" </p> </blockquote> <p>Even when leaving the sitename area blank, Google still adds the homepage title next to every single page. This only started hapening after I switched to my new current wordpress theme.</p> <p>I am using the Yoast SEO Plugin and even tried removing "%%sep%% %%sitename%%" in the settings, but still doesn't work.</p> <p>I contacted the theme developer, this was his response:</p> <blockquote> <p>"The theme doesn't set any custom title. It uses default add_theme_support( 'title-tag' ); wordpress function and Seo by Yoast works with this."</p> </blockquote> <p>How can I remove the sitename? Do I need to change the header.php code? If not which code should I edit?</p>
[ { "answer_id": 223346, "author": "Monkey Puzzle", "author_id": 48568, "author_profile": "https://wordpress.stackexchange.com/users/48568", "pm_score": 1, "selected": false, "text": "<p>In your header.php you may need to replace:</p>\n\n<pre><code>&lt;title&gt;&lt;?php whatever code you find in your existing theme ?&gt;&lt;/title&gt;\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>&lt;title&gt;&lt;?php wp_title(''); ?&gt;&lt;/title&gt;\n</code></pre>\n\n<p>Make sure you make a copy first so you can revert back if you need to!</p>\n" }, { "answer_id": 223347, "author": "Jevuska", "author_id": 18731, "author_profile": "https://wordpress.stackexchange.com/users/18731", "pm_score": 3, "selected": false, "text": "<p>By default WordPress use <code>_wp_render_title_tag</code> to hook <code>wp_head</code> ( see <a href=\"https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/default-filters.php#L223\" rel=\"noreferrer\">here</a> )</p>\n\n<pre><code>add_action( 'wp_head', '_wp_render_title_tag', 1 );\n</code></pre>\n\n<p>This function is wrapper of <a href=\"https://developer.wordpress.org/reference/functions/wp_get_document_title/\" rel=\"noreferrer\"><code>wp_get_document_title</code></a> to show title tag on theme if <code>add_theme_support( 'title-tag' );</code> added in theme file <code>functions.php</code> ( commonly ). \n<a href=\"https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/general-template.php#L944\" rel=\"noreferrer\">https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/general-template.php#L944</a></p>\n\n<p>If you see filter <a href=\"https://developer.wordpress.org/reference/hooks/document_title_parts/\" rel=\"noreferrer\"><code>document_title_parts</code></a> on function <a href=\"https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/general-template.php#L827\" rel=\"noreferrer\"><code>wp_get_document_title()</code></a>, we can filter parameters that used in title ( <code>title</code>, <code>page</code>, <code>tagline</code>, <code>site</code> ).</p>\n\n<p>Let say if we need to <strong>remove site name title part of homepage and single post</strong>, you just need to unset parameter <code>title</code> and <code>site</code> with <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"noreferrer\">conditional tags</a>, here the sample code ( add in <code>functions.php</code> theme file ):</p>\n\n<pre><code>add_filter( 'document_title_parts', function( $title )\n{\n if ( is_home() || is_front_page() )\n unset( $title['title'] ); /** Remove title name */\n\n if ( is_single() )\n unset( $title['site'] ); /** Remove site name */\n\n return $title;\n\n}, 10, 1 );\n</code></pre>\n\n<p>About your issue in Google indexing, it's off-topic here.</p>\n" } ]
2016/04/11
[ "https://wordpress.stackexchange.com/questions/223325", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92164/" ]
After switching to a different wordpress theme, Google started adding a sitename to ALL page titles in the search results. E.g.: > > "Page title - Sitename" > > > Even when leaving the sitename area blank, Google still adds the homepage title next to every single page. This only started hapening after I switched to my new current wordpress theme. I am using the Yoast SEO Plugin and even tried removing "%%sep%% %%sitename%%" in the settings, but still doesn't work. I contacted the theme developer, this was his response: > > "The theme doesn't set any custom title. It uses default add\_theme\_support( 'title-tag' ); wordpress function and Seo by Yoast works with this." > > > How can I remove the sitename? Do I need to change the header.php code? If not which code should I edit?
By default WordPress use `_wp_render_title_tag` to hook `wp_head` ( see [here](https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/default-filters.php#L223) ) ``` add_action( 'wp_head', '_wp_render_title_tag', 1 ); ``` This function is wrapper of [`wp_get_document_title`](https://developer.wordpress.org/reference/functions/wp_get_document_title/) to show title tag on theme if `add_theme_support( 'title-tag' );` added in theme file `functions.php` ( commonly ). <https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/general-template.php#L944> If you see filter [`document_title_parts`](https://developer.wordpress.org/reference/hooks/document_title_parts/) on function [`wp_get_document_title()`](https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/general-template.php#L827), we can filter parameters that used in title ( `title`, `page`, `tagline`, `site` ). Let say if we need to **remove site name title part of homepage and single post**, you just need to unset parameter `title` and `site` with [conditional tags](https://codex.wordpress.org/Conditional_Tags), here the sample code ( add in `functions.php` theme file ): ``` add_filter( 'document_title_parts', function( $title ) { if ( is_home() || is_front_page() ) unset( $title['title'] ); /** Remove title name */ if ( is_single() ) unset( $title['site'] ); /** Remove site name */ return $title; }, 10, 1 ); ``` About your issue in Google indexing, it's off-topic here.
223,333
<p>In a Twenty Thirteen child theme I append a menu item (a link to <a href="https://wordpress.stackexchange.com/questions/222638/how-to-pass-a-numeric-id-to-a-page-template">/player-number</a> page template, where the number is different for each user and represents her or his id in a game database) using the <a href="https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/" rel="nofollow noreferrer">wp_nav_menu_items</a> hook:</p> <pre><code>function my_nav_menu_items( $items ) { $profile = sprintf('&lt;li id="menu-item-32" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-32"&gt; &lt;a href="/player-%d/#navbar"&gt;Profile&lt;/a&gt;&lt;/li&gt;', 42); // 42 is just a placeholder here, representing user id return $items . $profile; } add_filter( 'wp_nav_menu_items', 'my_nav_menu_items' ); </code></pre> <p>And that item is visible and clickable in the <code>primary-menu</code>, but for some reason it is never highlighted (apologies for non-english text in the screenshot):</p> <p><a href="https://i.stack.imgur.com/iFmBh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iFmBh.png" alt="website screenshot"></a></p> <p>I.e. when I click at any other menu entry - it changes its color to reddish one and the font slant to <em>italics</em>:</p> <p><a href="https://i.stack.imgur.com/Zw25G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zw25G.png" alt="highlighted menu item"></a></p> <p>But the last menu item does not do that, why?</p> <p><strong>UPDATE:</strong></p> <p>The <a href="https://developer.wordpress.org/reference/hooks/wp_nav_menu_objects/" rel="nofollow noreferrer">wp_nav_menu_objects</a> filter seems to be more suitable for the task of adding a menu item and I have tried using it in my <a href="https://github.com/afarber/wp-newbie/blob/master/twentythirteen-child/functions.php" rel="nofollow noreferrer">/wp-content/themes/twentythirteen-child/functions.php</a> file:</p> <pre><code>function my_nav_menu_objects( $sorted_menu_items ) { $link = array ( 'title' =&gt; 'Profile', 'menu_item_parent' =&gt; 0, 'ID' =&gt; 32, 'url' =&gt; '/player-42', ); $sorted_menu_items[] = (object) $link; error_log(print_r($sorted_menu_items, TRUE)); return $sorted_menu_items; } add_filter( 'wp_nav_menu_objects', 'my_nav_menu_objects' ); </code></pre> <p>but it suffers the same problem: the menu item is added, but it is not highlighted (the CSS style <code>current-menu-item</code> for that is missing) when selected.</p> <p><strong>UPDATE 2:</strong></p> <p>Also I have tried adding a menu item called "Profile" manually and then searching and replacing its <code>url</code> with the following code:</p> <pre><code>function my_nav_menu_objects( $sorted_menu_items ) { foreach ( $sorted_menu_items as $item ) { error_log(print_r($item, TRUE)); if ( $item-&gt;title == 'Profile' ) { $item-&gt;url = '/player-42'; break; } } return $sorted_menu_items; } add_filter( 'wp_nav_menu_objects', 'my_nav_menu_objects' ); </code></pre> <p>with the same effect (the URL has changed, but CSS highlighting is missing, when that URL is selected).</p>
[ { "answer_id": 223343, "author": "Monkey Puzzle", "author_id": 48568, "author_profile": "https://wordpress.stackexchange.com/users/48568", "pm_score": 0, "selected": false, "text": "<p>The other pages show a 'current menu item' css state: </p>\n\n<pre><code>.nav-menu .current_page_item &gt; a, .nav-menu .current_page_ancestor &gt; a, .nav-menu .current-menu-item &gt; a, .nav-menu .current-menu-ancestor &gt; a {\n color: #bc360a;\n font-style: italic;\n</code></pre>\n\n<p>This page is showing as 'page-id-32'. If that corresponds to the page in the menu it should show the 'current page item' css. Otherwise you need to get the class 'current-menu-item' in the css somehow when you are on that page. For instance, if you change:</p>\n\n<pre><code>sprintf('&lt;li id=\"menu-item-32\" \n class=\"menu-item menu-item-type-custom \n menu-item-object-custom menu-item-32\"&gt;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>sprintf('&lt;li id=\"menu-item-32\" \n class=\"menu-item menu-item-type-custom \n menu-item-object-custom current-menu-item\"&gt;\n</code></pre>\n\n<p>It will do the job, but I think that would show as 'always' the current page.</p>\n" }, { "answer_id": 223445, "author": "Alexander Farber", "author_id": 41372, "author_profile": "https://wordpress.stackexchange.com/users/41372", "pm_score": 0, "selected": false, "text": "<p>Here is my own solution - in the <a href=\"https://github.com/afarber/wp-newbie/blob/master/twentythirteen-child/functions.php\" rel=\"nofollow\">/wp-content/themes/twentythirteen-child/functions.php</a> file add the <code>current-menu-item</code> CSS style if the page slug is <code>player</code>:</p>\n\n<pre><code>function my_nav_menu_items( $items ) \n{\n $profile = sprintf('&lt;li class=\"menu-item \n menu-item-type-custom \n menu-item-object-custom \n %s\"&gt;&lt;a href=\"/player-%d/#navbar\"&gt;Profile&lt;/a&gt;&lt;/li&gt;', \n ( is_page( 'player' ) ? 'current-menu-item' : '' ),\n 42);\n return $items . $profile;\n}\n\nadd_filter( 'wp_nav_menu_items', 'my_nav_menu_items' );\n</code></pre>\n\n<p>A more specific page check would be: <code>is_page( array ( 42, 'player' ) )</code></p>\n" }, { "answer_id": 223447, "author": "Jevuska", "author_id": 18731, "author_profile": "https://wordpress.stackexchange.com/users/18731", "pm_score": 2, "selected": true, "text": "<p><em>@AlexanderFarber</em>, there are many way to attach attribute class under <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu</code></a> link. I agree with <em>@Sumit</em>, adding page links in <code>Appearance &gt; Menu</code> WordPress take care of <code>current-menu-item</code> class or <code>current_page_item</code> class. Also, this way is best practice to handle your nav menu in the future.</p>\n<h3>Create dynamic link in wp_nav_menu</h3>\n<p>Since your question related to <a href=\"https://wordpress.stackexchange.com/a/222680/18731\">this answer</a>, then you have a <strong>Page</strong> with <code>player</code> as slug. My approach, after I add those page as menu in <code>Appearance &gt; Menu</code> ( then change label with 'Profile' ), I will use filter <a href=\"https://developer.wordpress.org/reference/hooks/nav_menu_link_attributes/\" rel=\"nofollow noreferrer\"><code>nav_menu_link_attributes</code></a> to make this page have dynamic link. As your question, you use current user id to make it dynamics. Take a look this sample code, say <code>7</code> is post/page ID as target:</p>\n<pre><code>add_filter( 'nav_menu_link_attributes', function( $atts, $item, $args, $depth )\n{\n // check our nav_menu\n if ( is_object( $args ) &amp;&amp; is_object( $item ) &amp;&amp; 'primary-menu' == $args-&gt;menu_id )\n {\n $post_id = 7; // Define Post or Page ID\n $user = wp_get_current_user();\n if ( 0 &lt; $user-&gt;ID &amp;&amp; $post_id == $item-&gt;object_id )\n $atts['href'] = esc_url( user_trailingslashit( untrailingslashit( $item-&gt;url ) . '-' . $user-&gt;ID ) );\n }\n return $atts;\n} 10, 4 );\n</code></pre>\n<p>You need to check which menu before you make change, since your filter will effect another menu in the same page. By this approach you don't get trouble in attribute ( class or id theme css related ) of the current page.</p>\n<p><strong>Answer related your code</strong></p>\n<p>Yes I know you need to add custom link by filter <code>wp_nav_menu_items</code> and add class attribute for the current page, almost the same with your answer. Since it related to Page, I use <code>current_page_item</code> as class attribute that match with css TwentyThirteen to make highlight of item nav menu.</p>\n<pre><code>add_filter( 'wp_nav_menu_items', 'my_nav_menu_items', 10, 2 );\nfunction my_nav_menu_items( $items, $args )\n{\n if ( is_object( $args ) &amp;&amp; 'primary-menu' == $args-&gt;menu_id )\n {\n $user = wp_get_current_user();\n $with_user_id = ( 0 != $user-&gt;ID ) ? '-' . $user-&gt;ID : '';\n \n $post_id = 7; // Post or Page ID\n $class = ( is_page( $post_id ) ) ? 'current_page_item' : '';\n \n $items .= sprintf( '&lt;li id=&quot;menu-item-32&quot; class=&quot;menu-item menu-item-type-custom \n menu-item-object-custom %1$s menu-item-32&quot;&gt;&lt;a href=&quot;%2$s&quot;&gt;%3$s&lt;/a&gt;&lt;/li&gt;',\n sanitize_html_class( $class ),\n esc_url( user_trailingslashit( untrailingslashit( get_page_link( $post_id ) ) . $with_user_id ) ),\n __( 'Profile', 'textdomain' )\n );\n }\n return $items;\n}\n</code></pre>\n<p>You can tweak the code to adjust with your current project. I hope this helps.</p>\n" } ]
2016/04/11
[ "https://wordpress.stackexchange.com/questions/223333", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41372/" ]
In a Twenty Thirteen child theme I append a menu item (a link to [/player-number](https://wordpress.stackexchange.com/questions/222638/how-to-pass-a-numeric-id-to-a-page-template) page template, where the number is different for each user and represents her or his id in a game database) using the [wp\_nav\_menu\_items](https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/) hook: ``` function my_nav_menu_items( $items ) { $profile = sprintf('<li id="menu-item-32" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-32"> <a href="/player-%d/#navbar">Profile</a></li>', 42); // 42 is just a placeholder here, representing user id return $items . $profile; } add_filter( 'wp_nav_menu_items', 'my_nav_menu_items' ); ``` And that item is visible and clickable in the `primary-menu`, but for some reason it is never highlighted (apologies for non-english text in the screenshot): [![website screenshot](https://i.stack.imgur.com/iFmBh.png)](https://i.stack.imgur.com/iFmBh.png) I.e. when I click at any other menu entry - it changes its color to reddish one and the font slant to *italics*: [![highlighted menu item](https://i.stack.imgur.com/Zw25G.png)](https://i.stack.imgur.com/Zw25G.png) But the last menu item does not do that, why? **UPDATE:** The [wp\_nav\_menu\_objects](https://developer.wordpress.org/reference/hooks/wp_nav_menu_objects/) filter seems to be more suitable for the task of adding a menu item and I have tried using it in my [/wp-content/themes/twentythirteen-child/functions.php](https://github.com/afarber/wp-newbie/blob/master/twentythirteen-child/functions.php) file: ``` function my_nav_menu_objects( $sorted_menu_items ) { $link = array ( 'title' => 'Profile', 'menu_item_parent' => 0, 'ID' => 32, 'url' => '/player-42', ); $sorted_menu_items[] = (object) $link; error_log(print_r($sorted_menu_items, TRUE)); return $sorted_menu_items; } add_filter( 'wp_nav_menu_objects', 'my_nav_menu_objects' ); ``` but it suffers the same problem: the menu item is added, but it is not highlighted (the CSS style `current-menu-item` for that is missing) when selected. **UPDATE 2:** Also I have tried adding a menu item called "Profile" manually and then searching and replacing its `url` with the following code: ``` function my_nav_menu_objects( $sorted_menu_items ) { foreach ( $sorted_menu_items as $item ) { error_log(print_r($item, TRUE)); if ( $item->title == 'Profile' ) { $item->url = '/player-42'; break; } } return $sorted_menu_items; } add_filter( 'wp_nav_menu_objects', 'my_nav_menu_objects' ); ``` with the same effect (the URL has changed, but CSS highlighting is missing, when that URL is selected).
*@AlexanderFarber*, there are many way to attach attribute class under [`wp_nav_menu`](https://developer.wordpress.org/reference/functions/wp_nav_menu/) link. I agree with *@Sumit*, adding page links in `Appearance > Menu` WordPress take care of `current-menu-item` class or `current_page_item` class. Also, this way is best practice to handle your nav menu in the future. ### Create dynamic link in wp\_nav\_menu Since your question related to [this answer](https://wordpress.stackexchange.com/a/222680/18731), then you have a **Page** with `player` as slug. My approach, after I add those page as menu in `Appearance > Menu` ( then change label with 'Profile' ), I will use filter [`nav_menu_link_attributes`](https://developer.wordpress.org/reference/hooks/nav_menu_link_attributes/) to make this page have dynamic link. As your question, you use current user id to make it dynamics. Take a look this sample code, say `7` is post/page ID as target: ``` add_filter( 'nav_menu_link_attributes', function( $atts, $item, $args, $depth ) { // check our nav_menu if ( is_object( $args ) && is_object( $item ) && 'primary-menu' == $args->menu_id ) { $post_id = 7; // Define Post or Page ID $user = wp_get_current_user(); if ( 0 < $user->ID && $post_id == $item->object_id ) $atts['href'] = esc_url( user_trailingslashit( untrailingslashit( $item->url ) . '-' . $user->ID ) ); } return $atts; } 10, 4 ); ``` You need to check which menu before you make change, since your filter will effect another menu in the same page. By this approach you don't get trouble in attribute ( class or id theme css related ) of the current page. **Answer related your code** Yes I know you need to add custom link by filter `wp_nav_menu_items` and add class attribute for the current page, almost the same with your answer. Since it related to Page, I use `current_page_item` as class attribute that match with css TwentyThirteen to make highlight of item nav menu. ``` add_filter( 'wp_nav_menu_items', 'my_nav_menu_items', 10, 2 ); function my_nav_menu_items( $items, $args ) { if ( is_object( $args ) && 'primary-menu' == $args->menu_id ) { $user = wp_get_current_user(); $with_user_id = ( 0 != $user->ID ) ? '-' . $user->ID : ''; $post_id = 7; // Post or Page ID $class = ( is_page( $post_id ) ) ? 'current_page_item' : ''; $items .= sprintf( '<li id="menu-item-32" class="menu-item menu-item-type-custom menu-item-object-custom %1$s menu-item-32"><a href="%2$s">%3$s</a></li>', sanitize_html_class( $class ), esc_url( user_trailingslashit( untrailingslashit( get_page_link( $post_id ) ) . $with_user_id ) ), __( 'Profile', 'textdomain' ) ); } return $items; } ``` You can tweak the code to adjust with your current project. I hope this helps.
223,357
<p>After testing I realized that Word Press after image upload will make medium and thumbnail sized images of original image <strong>without EXIF/IPTC info</strong></p> <p>I realized it is because GD image library is used on my host, and that is how GD library works by default, strip out all image info.</p> <p>After research I found out that if ImageMagick and the Imagick PHP extension is used instead of GD library EXIF info will be retained (with ImageMagick default settings) in generated resized image files.</p> <hr> <p><strong>UPDATE 1</strong></p> <p>ImageMagick and the Imagick PHP extension is installed on my host now. Now all generated images keep EXIF/IPTC info (original, medium and thumbnail image, all of them are with EXIF/IPTC data).</p> <p>I allow visitors to upload hi-res images on site, and in most cases visitors do not optimize/compress images before upload and sometimes image file size is quite big.</p> <p>For example 12MP image can be 10 MB, but after 85% jpeg compression its file size can be 2-3 times smaller, almost without noticeable loss of quality.</p> <p>I put this function to functions.php (my theme folder) to compress original image during upload, to save up disk space and speed up loading of hi-res image on page with it.</p> <pre><code>// Image compression on upload, compress original image function wt_handle_upload_callback( $data ) { $image_quality = 85; // 85% compression $file_path = $data['file']; $image = false; switch ( $data['type'] ) { case 'image/jpeg': { $image = imagecreatefromjpeg( $file_path ); imagejpeg( $image, $file_path, $image_quality ); break; } case 'image/png': { $image = imagecreatefrompng( $file_path ); imagepng( $image, $file_path, $image_quality ); break; } case 'image/gif': { // Nothing to do break; } } return $data; } add_filter( 'wp_handle_upload', 'wt_handle_upload_callback' ); </code></pre> <p>It works fine, original image is compressed, BUT this function removes EXIF/IPTC data on all images (I need to keep EXIT, at least on original image). Without function above, original and all resized images are with EXIF/IPTC data (because ImageMagick is installed), but original image is not compresed than.</p> <p>How to fix, adjust function above to keep EXIF?</p> <p><strong>UPDATE 2</strong></p> <p>WP 4.5 is reseased with some image hadling improvements, and also with option to preserve image EXIF data (in case ImageMagic is used on host, which is in my case). WP 4.5 introduced new filter "image_strip_meta" which can be used to keep or remove EXIF on generated resized images (medium and thumbnails).</p> <p>Can this filter be used to keep EXIF in original image when function above for compressiong original image (which remove all EXIF data from original and all resized image version) is used?</p> <p>Or, anything else which will result in compressing original image right after upload and keep EXIF in original image?</p>
[ { "answer_id": 223438, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": -1, "selected": false, "text": "<p>You should not assume that image related metadata survives the wordpress image manipulation. As you found out it depends on the image manipulation library installed on the server, and actually in version 4.5 the aim would be to strip some of it as noted here <a href=\"https://make.wordpress.org/core/2016/03/12/performance-improvements-for-images-in-wordpress-4-5/\" rel=\"nofollow\">https://make.wordpress.org/core/2016/03/12/performance-improvements-for-images-in-wordpress-4-5/</a>.</p>\n\n<p>If you need the metadata as part of the thumbnail (and I fail to see why would you need it), you should just directly call the php image manipulation API, and then update the wordpress DB to set the proper fields as if the wordpress API handled it (probably can be done with some filters without changing the overall process too much)</p>\n" }, { "answer_id": 223687, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>The problem is that you are using functions from <a href=\"http://php.net/manual/es/book.image.php\" rel=\"nofollow\">GD library</a> to manipulate images, not functions from <a href=\"https://codex.wordpress.org/Class_Reference/WP_Image_Editor\" rel=\"nofollow\">WordPress Image API (<code>WP_Image_Editor</code> class)</a>. So, WordPress things doesn't apply to the generated image by your code.</p>\n\n<p>WordPress Image API uses ImageMagick if available, otherwise it uses GD library.</p>\n\n<p>In order to keep EXIF data:</p>\n\n<ol>\n<li>If GD library is used, you need to install PHP wih the <a href=\"http://php.net/manual/en/book.exif.php\" rel=\"nofollow\">EXIF exension</a> and configure PHP with <a href=\"http://php.net/manual/en/exif.installation.php\" rel=\"nofollow\"><code>--enable-exif</code> flag</a>.</li>\n<li>If ImageMagick is available, then WordPress will use it and <a href=\"https://make.wordpress.org/core/2016/03/12/performance-improvements-for-images-in-wordpress-4-5/\" rel=\"nofollow\">EXIF and other meta data is preserved</a>. Also, you have access to <code>image_strip_meta</code> filter (not availabe if GD library is used).</li>\n</ol>\n\n<p>As you have ImageMagick installed, you could use it instead of GD library. Or, maybe better, use WordPress API:</p>\n\n<pre><code>add_filter( 'wp_handle_upload', 'wt_handle_upload_callback' );\nfunction wt_handle_upload_callback( $data ) {\n\n // get instance of WP_Image_Editor class\n $image = wp_get_image_editor( $data['file'] );\n\n if( ! is_wp_error( $image ) ) {\n $image-&gt;set_quality( 85 );\n $image-&gt;save( $data['file'], $data['type'] );\n }\n\n return $data;\n}\n</code></pre>\n\n<p><strong>I've not tested the above code</strong> and I think you don't need it. If the only prupose of doing all of this is to compress the image, you must know that the image is already compressed by WordPress to 82% quality (<a href=\"https://make.wordpress.org/core/2016/03/12/performance-improvements-for-images-in-wordpress-4-5/\" rel=\"nofollow\">90 before WP 4.5</a>). If you need to change the compression quality just use <a href=\"https://developer.wordpress.org/reference/hooks/jpeg_quality/\" rel=\"nofollow\"><code>jpeg_quality</code> filter</a>:</p>\n\n<pre><code>add_filter( 'jpeg_quality', 'cyb_set_jpeg_quality' );\nfunction cyb_set_jpeg_quality() {\n return 85;\n}\n</code></pre>\n" } ]
2016/04/11
[ "https://wordpress.stackexchange.com/questions/223357", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25053/" ]
After testing I realized that Word Press after image upload will make medium and thumbnail sized images of original image **without EXIF/IPTC info** I realized it is because GD image library is used on my host, and that is how GD library works by default, strip out all image info. After research I found out that if ImageMagick and the Imagick PHP extension is used instead of GD library EXIF info will be retained (with ImageMagick default settings) in generated resized image files. --- **UPDATE 1** ImageMagick and the Imagick PHP extension is installed on my host now. Now all generated images keep EXIF/IPTC info (original, medium and thumbnail image, all of them are with EXIF/IPTC data). I allow visitors to upload hi-res images on site, and in most cases visitors do not optimize/compress images before upload and sometimes image file size is quite big. For example 12MP image can be 10 MB, but after 85% jpeg compression its file size can be 2-3 times smaller, almost without noticeable loss of quality. I put this function to functions.php (my theme folder) to compress original image during upload, to save up disk space and speed up loading of hi-res image on page with it. ``` // Image compression on upload, compress original image function wt_handle_upload_callback( $data ) { $image_quality = 85; // 85% compression $file_path = $data['file']; $image = false; switch ( $data['type'] ) { case 'image/jpeg': { $image = imagecreatefromjpeg( $file_path ); imagejpeg( $image, $file_path, $image_quality ); break; } case 'image/png': { $image = imagecreatefrompng( $file_path ); imagepng( $image, $file_path, $image_quality ); break; } case 'image/gif': { // Nothing to do break; } } return $data; } add_filter( 'wp_handle_upload', 'wt_handle_upload_callback' ); ``` It works fine, original image is compressed, BUT this function removes EXIF/IPTC data on all images (I need to keep EXIT, at least on original image). Without function above, original and all resized images are with EXIF/IPTC data (because ImageMagick is installed), but original image is not compresed than. How to fix, adjust function above to keep EXIF? **UPDATE 2** WP 4.5 is reseased with some image hadling improvements, and also with option to preserve image EXIF data (in case ImageMagic is used on host, which is in my case). WP 4.5 introduced new filter "image\_strip\_meta" which can be used to keep or remove EXIF on generated resized images (medium and thumbnails). Can this filter be used to keep EXIF in original image when function above for compressiong original image (which remove all EXIF data from original and all resized image version) is used? Or, anything else which will result in compressing original image right after upload and keep EXIF in original image?
The problem is that you are using functions from [GD library](http://php.net/manual/es/book.image.php) to manipulate images, not functions from [WordPress Image API (`WP_Image_Editor` class)](https://codex.wordpress.org/Class_Reference/WP_Image_Editor). So, WordPress things doesn't apply to the generated image by your code. WordPress Image API uses ImageMagick if available, otherwise it uses GD library. In order to keep EXIF data: 1. If GD library is used, you need to install PHP wih the [EXIF exension](http://php.net/manual/en/book.exif.php) and configure PHP with [`--enable-exif` flag](http://php.net/manual/en/exif.installation.php). 2. If ImageMagick is available, then WordPress will use it and [EXIF and other meta data is preserved](https://make.wordpress.org/core/2016/03/12/performance-improvements-for-images-in-wordpress-4-5/). Also, you have access to `image_strip_meta` filter (not availabe if GD library is used). As you have ImageMagick installed, you could use it instead of GD library. Or, maybe better, use WordPress API: ``` add_filter( 'wp_handle_upload', 'wt_handle_upload_callback' ); function wt_handle_upload_callback( $data ) { // get instance of WP_Image_Editor class $image = wp_get_image_editor( $data['file'] ); if( ! is_wp_error( $image ) ) { $image->set_quality( 85 ); $image->save( $data['file'], $data['type'] ); } return $data; } ``` **I've not tested the above code** and I think you don't need it. If the only prupose of doing all of this is to compress the image, you must know that the image is already compressed by WordPress to 82% quality ([90 before WP 4.5](https://make.wordpress.org/core/2016/03/12/performance-improvements-for-images-in-wordpress-4-5/)). If you need to change the compression quality just use [`jpeg_quality` filter](https://developer.wordpress.org/reference/hooks/jpeg_quality/): ``` add_filter( 'jpeg_quality', 'cyb_set_jpeg_quality' ); function cyb_set_jpeg_quality() { return 85; } ```
223,473
<p>I am trying to wrap any iframe/embed in my content with some Facebook Instant Articles friendly code (only for that feed). I have it working, but it adds this code to oEmbed output as well which adds in a wrapper that is not needed (since the Facebook Instant Articles already handles oEmbed embeds).</p> <p>Basically, how can I get the wrap on iframes/embeds to happen before the oEmbed stuff happens?</p> <p>Below is the code I have:</p> <pre><code>function wrap_iframe( $content ) { if (is_feed( INSTANT_ARTICLES_SLUG )) { // Match any iframes or embeds $pattern = '~&lt;iframe.*&lt;/iframe&gt;|&lt;embed.*&lt;/embed&gt;~'; preg_match_all( $pattern, $content, $matches ); foreach ( $matches[0] as $match ) { $wrappedframe = '&lt;figure class="op-interactive"&gt;&lt;iframe&gt;' . $match . '&lt;/iframe&gt;&lt;/figure&gt;'; $content = str_replace($match, $wrappedframe, $content); } return $content; } } add_filter( 'the_content', 'wrap_iframe' ); </code></pre>
[ { "answer_id": 223649, "author": "mikko-lauhakari", "author_id": 52039, "author_profile": "https://wordpress.stackexchange.com/users/52039", "pm_score": 1, "selected": true, "text": "<p>I think you might have to modify the plugin, fork it, if you like the rest of it's functionality.</p>\n\n<p>Then add functionality that when you \"favourite\" a post/image, instead of adding it to your favourites you get a list which collection you want to add it to.\nAll of these collections could have their own url like www.mysite.com/user/collections/collection-name .</p>\n" }, { "answer_id": 223754, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow\">Register a collection post type</a> to represent a single collection. You'll get permalinks and rewrite rules to resolve the requests for free.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow\">Insert a new collection post</a> for a user when they create a collection, and save the chosen post IDs as an array in <a href=\"https://codex.wordpress.org/Custom_Fields\" rel=\"nofollow\">post meta</a>. You can pass that array directly as <code>post__in</code> argument in a <code>WP_Query</code> instance to load the posts in the array.</p>\n" } ]
2016/04/12
[ "https://wordpress.stackexchange.com/questions/223473", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90859/" ]
I am trying to wrap any iframe/embed in my content with some Facebook Instant Articles friendly code (only for that feed). I have it working, but it adds this code to oEmbed output as well which adds in a wrapper that is not needed (since the Facebook Instant Articles already handles oEmbed embeds). Basically, how can I get the wrap on iframes/embeds to happen before the oEmbed stuff happens? Below is the code I have: ``` function wrap_iframe( $content ) { if (is_feed( INSTANT_ARTICLES_SLUG )) { // Match any iframes or embeds $pattern = '~<iframe.*</iframe>|<embed.*</embed>~'; preg_match_all( $pattern, $content, $matches ); foreach ( $matches[0] as $match ) { $wrappedframe = '<figure class="op-interactive"><iframe>' . $match . '</iframe></figure>'; $content = str_replace($match, $wrappedframe, $content); } return $content; } } add_filter( 'the_content', 'wrap_iframe' ); ```
I think you might have to modify the plugin, fork it, if you like the rest of it's functionality. Then add functionality that when you "favourite" a post/image, instead of adding it to your favourites you get a list which collection you want to add it to. All of these collections could have their own url like www.mysite.com/user/collections/collection-name .
223,491
<p>I have just upgraded to wordpress 4.5 and now my custom logo for the admin doesn't work, the theme which I built uses the following in the theme functions.php:</p> <pre><code>/* change admin logo */ function my_login_logo() { ?&gt; &lt;style type="text/css"&gt; .login h1 a { background-image: url(&lt;?php echo get_field('logo','options'); ?&gt;); background-position: center center; background-repeat: no-repeat; background-size: cover; width: 320px !important; height: 99px !important; margin-bottom: 20px !important; } .login form { margin-top: 0px; } &lt;/style&gt; &lt;?php } add_action( 'login_enqueue_scripts', 'my_login_logo' ); </code></pre> <p>I cannot find a work around for this, can anyone help?</p>
[ { "answer_id": 223492, "author": "WiTon Nope", "author_id": 84518, "author_profile": "https://wordpress.stackexchange.com/users/84518", "pm_score": 2, "selected": true, "text": "<p>I think you have the logo called from the Theme Options try updating your Theme Options alternatively you have many plugins that can help you achieve that.\nLike:<br>\n<a href=\"https://wordpress.org/plugins/add-logo-to-admin/\" rel=\"nofollow\">https://wordpress.org/plugins/add-logo-to-admin/</a></p>\n\n<p>You can always refer to the Wordpress Codes</p>\n\n<p><a href=\"https://codex.wordpress.org/Customizing_the_Login_Form\" rel=\"nofollow\">https://codex.wordpress.org/Customizing_the_Login_Form</a></p>\n" }, { "answer_id": 224210, "author": "Mav2287", "author_id": 92658, "author_profile": "https://wordpress.stackexchange.com/users/92658", "pm_score": 0, "selected": false, "text": "<p>Add !important; to EVERYTHING and that should solve your problem. You don't have your first 4 background items as !important; so they are being overridden. This is why it doesn't work anymore.</p>\n" }, { "answer_id": 224692, "author": "Jim Ellis", "author_id": 92943, "author_profile": "https://wordpress.stackexchange.com/users/92943", "pm_score": 0, "selected": false, "text": "<p>You might try changing the class login to an id login. Replace .login h1 a {...} with #login h1 a {...}.</p>\n" }, { "answer_id": 227528, "author": "Erik Almén", "author_id": 94530, "author_profile": "https://wordpress.stackexchange.com/users/94530", "pm_score": 0, "selected": false, "text": "<p>I just added the id (#login h1 a) to the function and that worked fine.</p>\n\n<pre><code>function my_login_logo() { ?&gt;\n &lt;style type=\"text/css\"&gt;\n #login h1 a, .login h1 a {\n background-image: url(&lt;?php echo get_stylesheet_directory_uri(); ?&gt;/images/login-logo_320px.png);\n padding-bottom: 30px;background-size:160px 160px;width:160px;height:160px;\n }\n .login form {\n background: #f1f1f1 none repeat scroll 0 0;\n border: 1px solid rgba(14, 118, 188, 0.5);\n box-shadow: 0 0 0 rgba(0, 0, 0, 0.13);\n }\n &lt;/style&gt;\n&lt;?php }\nadd_action( 'login_enqueue_scripts', 'my_login_logo' );\n</code></pre>\n" } ]
2016/04/12
[ "https://wordpress.stackexchange.com/questions/223491", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91532/" ]
I have just upgraded to wordpress 4.5 and now my custom logo for the admin doesn't work, the theme which I built uses the following in the theme functions.php: ``` /* change admin logo */ function my_login_logo() { ?> <style type="text/css"> .login h1 a { background-image: url(<?php echo get_field('logo','options'); ?>); background-position: center center; background-repeat: no-repeat; background-size: cover; width: 320px !important; height: 99px !important; margin-bottom: 20px !important; } .login form { margin-top: 0px; } </style> <?php } add_action( 'login_enqueue_scripts', 'my_login_logo' ); ``` I cannot find a work around for this, can anyone help?
I think you have the logo called from the Theme Options try updating your Theme Options alternatively you have many plugins that can help you achieve that. Like: <https://wordpress.org/plugins/add-logo-to-admin/> You can always refer to the Wordpress Codes <https://codex.wordpress.org/Customizing_the_Login_Form>
223,536
<p>I am trying to move my javascript to the footer, however when moving jQuery, it breaks a slideshow.</p> <p>I am using the following to load jQuery in the footer:</p> <pre><code>wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', includes_url( '/js/jquery/jquery.js' ), false, NULL, true ); wp_enqueue_script( 'jquery' ); </code></pre> <p>I am then trying to load this AFTER jQuery using this:</p> <pre><code>function myscript() { ?&gt; &lt;script type="text/javascript"&gt; (function($){ $(window).load(function(){ /* full width slider */ $('#slider').iosSlider({ snapToChildren: true, desktopClickDrag: true, snapFrictionCoefficient: 0.8, autoSlideTransTimer: 500, infiniteSlider:true, autoSlide: true, autoSlideTimer: 5000, navPrevSelector: $('.next_&lt;?php echo $sliderrandomid; ?&gt;'), navNextSelector: $('.prev_&lt;?php echo $sliderrandomid; ?&gt;'), onSliderLoaded: startSlider, onSlideChange: slideChange, onSliderResize: slideResize, }); function slideChange(args) { } function slideResize(args) { } function startSlider(args){ } }) })(jQuery); &lt;/script&gt; &lt;?php } add_action( 'wp_footer', 'myscript' ); </code></pre> <p>I have tried adding:</p> <pre><code> if( wp_script_is( 'jquery', 'done' ) ) { //Script } </code></pre> <p>But unfortunately, the inline script doesn't load up.</p> <p>Is anyone able to give me any tips? I'm pretty much half way there, just need the inline script to load AFTER jQuery so it works.</p> <p>Thanks in advance!</p>
[ { "answer_id": 223543, "author": "Deepak jha", "author_id": 66318, "author_profile": "https://wordpress.stackexchange.com/users/66318", "pm_score": 2, "selected": false, "text": "<p>You are trying to load your inline js script after jQuery just by calling <code>add_action( 'wp_footer', 'myscript' );</code> after <code>wp_enqueue_script( 'jquery' );</code></p>\n\n<p>But this will not load your <code>myscript</code> after <code>jQuery</code>. It is not how <code>wp_footer</code> and <code>wp_enqueue_script</code> works.</p>\n\n<p><code>wp_footer</code> has a third argument named \"priority\". </p>\n\n<pre><code>add_action( 'wp_footer', 'your_function', 100 ); //100 is priority here. larger the priority later that script will be executed.\n</code></pre>\n\n<p>Enqueued scripts are executed at priority level 20 using <code>wp_footer</code>.</p>\n\n<p>And if you don't supply any third priority, script will be enqueued at priority 10 by default (Which means your script will be included before jQuery as you have not given any priority). </p>\n\n<p>So you need to call your function after priority 20.\nFor example:</p>\n\n<p><code>add_action( 'wp_footer', 'myscript',50 );</code></p>\n\n<p>try adding your script using above modification, it should work.</p>\n" }, { "answer_id": 223569, "author": "Caspar", "author_id": 27191, "author_profile": "https://wordpress.stackexchange.com/users/27191", "pm_score": 1, "selected": false, "text": "<p>Seems like you'd be better off saving your script in a <code>.js</code> file and then enqueuing your script using <code>wp_enqueue_script()</code> instead of <code>wp_footer</code>. That way you can designate jquery as a dependency for your script.</p>\n\n<pre><code>wp_enqueue_script( 'myscript', 'path/to/myscript.js', array( 'jquery' ), false, true );\n</code></pre>\n\n<p>This also separates your js out of your php into a proper asset that can be tracked and updated separately, which is a good practice to get into.</p>\n" } ]
2016/04/13
[ "https://wordpress.stackexchange.com/questions/223536", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/72787/" ]
I am trying to move my javascript to the footer, however when moving jQuery, it breaks a slideshow. I am using the following to load jQuery in the footer: ``` wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', includes_url( '/js/jquery/jquery.js' ), false, NULL, true ); wp_enqueue_script( 'jquery' ); ``` I am then trying to load this AFTER jQuery using this: ``` function myscript() { ?> <script type="text/javascript"> (function($){ $(window).load(function(){ /* full width slider */ $('#slider').iosSlider({ snapToChildren: true, desktopClickDrag: true, snapFrictionCoefficient: 0.8, autoSlideTransTimer: 500, infiniteSlider:true, autoSlide: true, autoSlideTimer: 5000, navPrevSelector: $('.next_<?php echo $sliderrandomid; ?>'), navNextSelector: $('.prev_<?php echo $sliderrandomid; ?>'), onSliderLoaded: startSlider, onSlideChange: slideChange, onSliderResize: slideResize, }); function slideChange(args) { } function slideResize(args) { } function startSlider(args){ } }) })(jQuery); </script> <?php } add_action( 'wp_footer', 'myscript' ); ``` I have tried adding: ``` if( wp_script_is( 'jquery', 'done' ) ) { //Script } ``` But unfortunately, the inline script doesn't load up. Is anyone able to give me any tips? I'm pretty much half way there, just need the inline script to load AFTER jQuery so it works. Thanks in advance!
You are trying to load your inline js script after jQuery just by calling `add_action( 'wp_footer', 'myscript' );` after `wp_enqueue_script( 'jquery' );` But this will not load your `myscript` after `jQuery`. It is not how `wp_footer` and `wp_enqueue_script` works. `wp_footer` has a third argument named "priority". ``` add_action( 'wp_footer', 'your_function', 100 ); //100 is priority here. larger the priority later that script will be executed. ``` Enqueued scripts are executed at priority level 20 using `wp_footer`. And if you don't supply any third priority, script will be enqueued at priority 10 by default (Which means your script will be included before jQuery as you have not given any priority). So you need to call your function after priority 20. For example: `add_action( 'wp_footer', 'myscript',50 );` try adding your script using above modification, it should work.
223,552
<p>I used <code>wp_list_table</code> class to create my custom table in the backend. It's working fine. </p> <p>Now, I want to add filters like in the below image. <a href="https://i.stack.imgur.com/Fe89m.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Fe89m.png" alt="enter image description here"></a></p> <p>Here is my existing code to render admin table with my custom information's. </p> <pre><code>if( ! class_exists( 'WP_List_Table' ) ) { require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ); } class Kv_subscribers_list extends WP_List_Table { function __construct(){ global $status, $page; parent::__construct( array( 'singular' =&gt; 'notification', 'plural' =&gt; 'notifications', 'ajax' =&gt; false ) ); } function column_default($item, $column_name){ switch($column_name){ case 'email': case 'date': case 'common': case 'unit_id': return $item[$column_name]; default: return print_r($item,true); //Show the whole array for troubleshooting purposes } } function column_email($item){ $actions = array( 'email' =&gt; sprintf('&lt;a href="?page=%s&amp;action=%s&amp;email_id=%s"&gt;E-mail&lt;/a&gt;',$_REQUEST['page'],'email',$item['id']), 'delete' =&gt; sprintf('&lt;a href="?page=%s&amp;action=%s&amp;delete_id=%s"&gt;Delete&lt;/a&gt;',$_REQUEST['page'],'delete',$item['id']), ); //Return the title contents return sprintf('%1$s %2$s', /*$1%s*/ $item['email'], /*$2%s*/ $this-&gt;row_actions($actions) ); } function column_cb($item){ return sprintf( '&lt;input type="checkbox" name="%1$s[]" value="%2$s" /&gt;', /*$1%s*/ $this-&gt;_args['singular'], /*$2%s*/ $item['id'] ); } function get_columns(){ $columns = array( 'cb' =&gt; '&lt;input type="checkbox" /&gt;', //Render a checkbox instead of text 'email'=&gt;__('Date'), 'date'=&gt;__('Date'), 'common'=&gt;__('Common Alert'), 'unit_id'=&gt;__('Unique ID') ); return $columns; } public function get_sortable_columns() { $sortable_columns = array( 'email' =&gt; array('wp_user_id',false), //true means it's already sorted 'date' =&gt; array('date',false), 'common' =&gt; array('common',false) ); return $sortable_columns; } public function get_bulk_actions() { $actions = array( 'delete' =&gt; 'Delete', 'email' =&gt; 'Email' ); return $actions; } public function process_bulk_action() { global $wpdb; $notifications_tbl = $wpdb-&gt;prefix.'newsletter'; if( 'delete'===$this-&gt;current_action() ) { foreach($_POST['notification'] as $single_val){ $wpdb-&gt;delete( $notifications_tbl, array( 'id' =&gt; (int)$single_val ) ); } $redirect_url = get_admin_url( null, 'admin.php?page=subscribers' ); wp_safe_redirect($redirect_url); wp_die('Items deleted (or they would be if we had items to delete)!'); } if( 'email'===$this-&gt;current_action() ) { $result_email_ar = implode("-",$_POST['notification']); $redirect_url = get_admin_url( null, 'admin.php?page=kvcodes&amp;ids='.$result_email_ar ); wp_safe_redirect($redirect_url); wp_die(' '); } } function prepare_items() { global $wpdb; //This is used only if making any database queries $database_name = $wpdb-&gt;prefix.'newsletter' ; $per_page = 10; $query = "SELECT * FROM $database_name ORDER BY id DESC"; $columns = $this-&gt;get_columns(); $hidden = array(); $sortable = $this-&gt;get_sortable_columns(); $this-&gt;_column_headers = array($columns, $hidden, $sortable); $this-&gt;process_bulk_action(); $data = $wpdb-&gt;get_results($query, ARRAY_A ); function usort_reorder($a,$b){ $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'title'; //If no sort, default to title $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc'; //If no order, default to asc $result = strcmp($a[$orderby], $b[$orderby]); //Determine sort order return ($order==='asc') ? $result : -$result; //Send final sort direction to usort } // usort($data, 'usort_reorder'); $current_page = $this-&gt;get_pagenum(); $total_items = count($data); $data = array_slice($data,(($current_page-1)*$per_page),$per_page); $this-&gt;items = $data; $this-&gt;set_pagination_args( array( 'total_items' =&gt; $total_items, //WE have to calculate the total number of items 'per_page' =&gt; $per_page, //WE have to determine how many items to show on a page 'total_pages' =&gt; ceil($total_items/$per_page) //WE have to calculate the total number of pages ) ); } }//class </code></pre> <p>and </p> <pre><code>echo '&lt;form method="post"&gt;'; $mydownloads = new Kv_subscribers_list(); echo '&lt;/pre&gt;&lt;div class="wrap"&gt;&lt;h2&gt;Subscribers&lt;a href="'."http://".$_SERVER["SERVER_NAME"].$_SERVER['REQUEST_URI'].'&amp;add_new=true" class="add-new-h2"&gt;Add New&lt;/a&gt;&lt;/h2&gt;'; $mydownloads-&gt;prepare_items(); $mydownloads-&gt;display(); echo '&lt;/div&gt;&lt;/form&gt;'; </code></pre> <p>Now, I want to make the filters like </p> <blockquote> <p>All || Published || Trash</p> </blockquote> <p>I need to create a custom filter like this. </p>
[ { "answer_id": 223846, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 4, "selected": false, "text": "<p><strong>Code</strong>\n\n\n<pre><code>class Kv_subscribers_list extends WP_List_Table {\n\nfunction __construct(){\n global $status, $page; \n\n parent::__construct( array(\n 'singular' =&gt; 'notification', \n 'plural' =&gt; 'notifications', \n 'ajax' =&gt; false \n ) ); \n}\n\nprotected function get_views() { \n $status_links = array(\n \"all\" =&gt; __(\"&lt;a href='#'&gt;All&lt;/a&gt;\",'my-plugin-slug'),\n \"published\" =&gt; __(\"&lt;a href='#'&gt;Published&lt;/a&gt;\",'my-plugin-slug'),\n \"trashed\" =&gt; __(\"&lt;a href='#'&gt;Trashed&lt;/a&gt;\",'my-plugin-slug')\n );\n return $status_links;\n}\n\nfunction column_default($item, $column_name){\n switch($column_name){\n case 'email':\n case 'date':\n case 'common': \n case 'unit_id': \n return $item[$column_name];\n default:\n return print_r($item,true); //Show the whole array for troubleshooting purposes\n }\n}\n\nfunction column_email($item){ \n $actions = array(\n 'email' =&gt; sprintf('&lt;a href=\"?page=%s&amp;action=%s&amp;email_id=%s\"&gt;E-mail&lt;/a&gt;',$_REQUEST['page'],'email',$item['id']),\n 'delete' =&gt; sprintf('&lt;a href=\"?page=%s&amp;action=%s&amp;delete_id=%s\"&gt;Delete&lt;/a&gt;',$_REQUEST['page'],'delete',$item['id']),\n );\n\n //Return the title contents\n return sprintf('%1$s %2$s',\n /*$1%s*/ $item['email'], \n /*$2%s*/ $this-&gt;row_actions($actions)\n );\n}\n\nfunction column_cb($item){\n return sprintf(\n '&lt;input type=\"checkbox\" name=\"%1$s[]\" value=\"%2$s\" /&gt;',\n /*$1%s*/ $this-&gt;_args['singular'], \n /*$2%s*/ $item['id'] \n );\n}\n\nfunction get_columns(){\n $columns = array(\n 'cb' =&gt; '&lt;input type=\"checkbox\" /&gt;', \n 'email'=&gt;__('Email'), \n 'date'=&gt;__('Date'), \n 'common'=&gt;__('Common Alert'), \n 'unit_id'=&gt;__('Unique ID')\n );\n return $columns;\n}\npublic function get_sortable_columns() {\n $sortable_columns = array(\n 'email' =&gt; array('wp_user_id',false), //true means it's already sorted\n 'date' =&gt; array('date',false),\n 'common' =&gt; array('common',false)\n );\n return $sortable_columns;\n}\npublic function get_bulk_actions() {\n $actions = array(\n 'delete' =&gt; 'Delete',\n 'email' =&gt; 'Email'\n );\n return $actions;\n}\n\npublic function process_bulk_action() {\n\n global $wpdb; \n $notifications_tbl = $wpdb-&gt;prefix.'newsletter';\n\n if( 'delete'===$this-&gt;current_action() ) {\n foreach($_POST['notification'] as $single_val){\n $wpdb-&gt;delete( $notifications_tbl, array( 'id' =&gt; (int)$single_val ) ); \n }\n $redirect_url = get_admin_url( null, 'admin.php?page=subscribers' );\n wp_safe_redirect($redirect_url); \n wp_die('Items deleted (or they would be if we had items to delete)!');\n } \n if( 'email'===$this-&gt;current_action() ) { \n $result_email_ar = implode(\"-\",$_POST['notification']);\n $redirect_url = get_admin_url( null, 'admin.php?page=kvcodes&amp;ids='.$result_email_ar );\n wp_safe_redirect($redirect_url); \n\n wp_die(' ');\n } \n}\n\nfunction prepare_items() {\n global $wpdb; //This is used only if making any database queries\n $database_name = $wpdb-&gt;prefix.'newsletter' ;\n $per_page = 10;\n $query = \"SELECT * FROM $database_name ORDER BY id DESC\";\n\n $columns = $this-&gt;get_columns();\n $hidden = array();\n $sortable = $this-&gt;get_sortable_columns();\n\n $this-&gt;_column_headers = array($columns, $hidden, $sortable); \n\n $this-&gt;process_bulk_action();\n\n $data = $wpdb-&gt;get_results($query, ARRAY_A );\n\n function usort_reorder($a,$b){\n $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'title'; //If no sort, default to title\n $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc'; //If no order, default to asc\n $result = strcmp($a[$orderby], $b[$orderby]); //Determine sort order\n return ($order==='asc') ? $result : -$result; //Send final sort direction to usort\n }\n // usort($data, 'usort_reorder'); \n\n $current_page = $this-&gt;get_pagenum(); \n\n $total_items = count($data);\n\n $data = array_slice($data,(($current_page-1)*$per_page),$per_page); \n\n $this-&gt;items = $data;\n\n $this-&gt;set_pagination_args( array(\n 'total_items' =&gt; $total_items, //WE have to calculate the total number of items\n 'per_page' =&gt; $per_page, //WE have to determine how many items to show on a page\n 'total_pages' =&gt; ceil($total_items/$per_page) //WE have to calculate the total number of pages\n ) );\n}\n}//class\n</code></pre>\n\n<p><strong>Admin Page &amp; Rendering Sample</strong></p>\n\n<pre><code>function o_add_menu_items(){\n add_menu_page('Plugin List Table', 'Sub', 'activate_plugins', 'subscribers', 'o_render_list_page');\n} \nadd_action('admin_menu', 'o_add_menu_items');\n\nfunction o_render_list_page() {\n $mydownloads = new Kv_subscribers_list();\n $title = __(\"Subscribers\",\"my_plugin_slug\");\n ?&gt;\n &lt;div class=\"wrap\"&gt;\n &lt;h1&gt;\n &lt;?php echo esc_html( $title );?&gt;\n &lt;!-- Check edit permissions --&gt;\n &lt;a href=\"&lt;?php echo admin_url( 'admin.php?page=subscribers&amp;add_new=true' ); ?&gt;\" class=\"page-title-action\"&gt;\n &lt;?php echo esc_html_x('Add New', 'my-plugin-slug'); ?&gt;\n &lt;/a&gt;\n &lt;?php\n ?&gt;\n &lt;/h1&gt;\n &lt;/div&gt;\n &lt;?php $mydownloads-&gt;views(); ?&gt;\n &lt;form method=\"post\"&gt;\n &lt;?php \n\n $mydownloads-&gt;prepare_items(); \n $mydownloads-&gt;display();\n ?&gt;\n &lt;/form&gt;\n&lt;?php\n}\n</code></pre>\n\n<p><strong>Explanation</strong></p>\n\n<p>We need to override <code>WP_List_Table</code> class method <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-list-table.php#L378\" rel=\"noreferrer\">get_views</a> to get status links on the top.By default it is an empty array.</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-list-table.php#L388\" rel=\"noreferrer\">views</a> method of <code>WP_List_Table</code> uses <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-list-table.php#L378\" rel=\"noreferrer\">get_views</a> to display list of those links that we return in the <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-list-table.php#L378\" rel=\"noreferrer\">get_views</a> as an associative array with separator <code>|</code>.</p>\n\n<p>We can also override <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-list-table.php#L388\" rel=\"noreferrer\">views</a> method to have more control , for example if we want to change separator.</p>\n\n<p>Take a look at how other list tables are using that. For instance check <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-posts-list-table.php#L264\" rel=\"noreferrer\">WP_Posts_List_Table</a>.</p>\n\n<p>After you have overridden the method then place <code>$mydownloads-&gt;views();</code> .be sure to escape all and internationalize strings.</p>\n\n<p><strong>Using Filter</strong></p>\n\n<p>We can use <code>views_{$this-&gt;screen-&gt;id}</code> filter once we have added <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-list-table.php#L378\" rel=\"noreferrer\">get_views</a> method.\nAssuming <code>toplevel_page_subscribers</code> as screen id</p>\n\n<pre><code>add_filter('views_toplevel_page_subscribers','my_plugin_slug_status_links',10, 1);\n\nfunction my_plugin_slug_status_links($views) {\n $views['scheduled'] = \"&lt;a href='#'&gt;Scheduled&lt;/a&gt;\";\n return $views;\n}\n</code></pre>\n" }, { "answer_id": 371132, "author": "metita", "author_id": 191665, "author_profile": "https://wordpress.stackexchange.com/users/191665", "pm_score": 3, "selected": false, "text": "<p>Well, I know this is quite late, but since this is the first result in google when searching for WP_List_Table filtering, I must tell you that there's <code>extra_tablenav</code> function available to be overrode in your class extension:</p>\n<pre><code>class Kv_subscribers_list extends WP_List_Table {\n\n function extra_tablenav( $which )\n {\n switch ( $which )\n {\n case 'top':\n // Your html code to output\n break;\n\n case 'bottom':\n // Your html code to output\n break;\n }\n }\n}\n</code></pre>\n<p>If you want to output in both sections just ignore the switch and set your HTML code straight at the beginning of the function.</p>\n" }, { "answer_id": 395210, "author": "tranchau", "author_id": 176866, "author_profile": "https://wordpress.stackexchange.com/users/176866", "pm_score": 1, "selected": false, "text": "<p>You can use</p>\n<pre><code>&lt;?php\nclass Kv_subscribers_list extends WP_List_Table {\n\n function extra_tablenav( $which )\n {\n switch ( $which )\n {\n case 'top':\n // Your html code to output\n global $wpdb, $wp_locale;\n\n $extra_checks = &quot;AND status != 'auto-draft'&quot;;\n if ( ! isset( $_GET['status'] ) || 'trash' !== $_GET['status'] ) {\n $extra_checks .= &quot; AND status != 'trash'&quot;;\n } elseif ( isset( $_GET['status'] ) ) {\n $extra_checks = $wpdb-&gt;prepare( ' AND status = %s', $_GET['status'] );\n }\n\n $sql = &quot;\n SELECT DISTINCT YEAR( create_date ) AS year, MONTH( create_date ) AS month\n FROM &quot;.$wpdb-&gt;prefix.&quot;audio_record\n WHERE 1 = 1\n $extra_checks\n ORDER BY create_date DESC&quot;;\n \n $months = $wpdb-&gt;get_results(\n $wpdb-&gt;prepare(\n $sql\n )\n );\n $month_count = count( $months );\n\n if ( ! $month_count || ( 1 == $month_count &amp;&amp; 0 == $months[0]-&gt;month ) ) {\n return;\n }\n $m = isset( $_GET['m'] ) ? (int) $_GET['m'] : 0;\n\n $wp_query = add_query_arg();\n $wp_query = remove_query_arg('m');\n $link = esc_url_raw($wp_query);\n ?&gt;\n &lt;div class=&quot;alignleft actions&quot;&gt;\n &lt;select name=&quot;m&quot; id=&quot;filter-by-date&quot;&gt;\n &lt;option&lt;?php selected( $m, 0 ); ?&gt; value=&quot;0&quot; data-rc=&quot;&lt;?php _e($link); ?&gt;&quot;&gt;&lt;?php _e( 'All dates' ); ?&gt;&lt;/option&gt;\n &lt;?php\n\n foreach ( $months as $arc_row ) {\n if ( 0 == $arc_row-&gt;year ) {\n continue;\n }\n\n $month = zeroise( $arc_row-&gt;month, 2 );\n $year = $arc_row-&gt;year;\n\n $wp_query = add_query_arg('m', $arc_row-&gt;year . $month);\n $link = esc_url_raw($wp_query);\n\n printf(\n &quot;&lt;option %s value='%s' data-rc='%s'&gt;%s&lt;/option&gt;\\n&quot;,\n selected( $m, $year . $month, false ),\n esc_attr( $arc_row-&gt;year . $month ),\n esc_attr( $link),\n /* translators: 1: Month name, 2: 4-digit year. */\n sprintf( __( '%1$s %2$d' ), $wp_locale-&gt;get_month( $month ), $year )\n );\n }\n ?&gt;\n &lt;/select&gt;\n &lt;a href=&quot;javascript:void(0)&quot; class=&quot;button&quot; onclick=&quot;window.location.href = jQuery('#filter-by-date option:selected').data('rc');&quot;&gt;Filter&lt;/a&gt;\n &lt;/div&gt;\n &lt;?php\n break;\n break;\n\n case 'bottom':\n // Your html code to output\n break;\n }\n }\n}\n</code></pre>\n<p>and for action query, you can add code in</p>\n<blockquote>\n<p>public function prepare_items()</p>\n</blockquote>\n<blockquote>\n<p>or funtion get_customers<br />\n$this-&gt;items = self::get_customers($per_page, $current_page);</p>\n</blockquote>\n<pre><code>&lt;?php\n //public static function get_customers($per_page = 20, $page_number = 1) \n\n\n if (!empty($_REQUEST['m'])) {\n $search = $_REQUEST['m'];\n $year = substr($search,0,4);\n $month = substr($search,4,5);\n\n if(!empty($year)){\n $sql .= ' And YEAR(create_date)=&quot;' . $year . '&quot;';\n }\n if(!empty($month)){\n $sql .= ' And MONTH(create_date)=&quot;' . $month . '&quot;';\n }\n }\n</code></pre>\n<p>This is example for get form my database<br />\nWhen click Filter button will go to url from data-rc</p>\n<p><a href=\"https://i.stack.imgur.com/yygOg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yygOg.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2016/04/13
[ "https://wordpress.stackexchange.com/questions/223552", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43308/" ]
I used `wp_list_table` class to create my custom table in the backend. It's working fine. Now, I want to add filters like in the below image. [![enter image description here](https://i.stack.imgur.com/Fe89m.png)](https://i.stack.imgur.com/Fe89m.png) Here is my existing code to render admin table with my custom information's. ``` if( ! class_exists( 'WP_List_Table' ) ) { require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' ); } class Kv_subscribers_list extends WP_List_Table { function __construct(){ global $status, $page; parent::__construct( array( 'singular' => 'notification', 'plural' => 'notifications', 'ajax' => false ) ); } function column_default($item, $column_name){ switch($column_name){ case 'email': case 'date': case 'common': case 'unit_id': return $item[$column_name]; default: return print_r($item,true); //Show the whole array for troubleshooting purposes } } function column_email($item){ $actions = array( 'email' => sprintf('<a href="?page=%s&action=%s&email_id=%s">E-mail</a>',$_REQUEST['page'],'email',$item['id']), 'delete' => sprintf('<a href="?page=%s&action=%s&delete_id=%s">Delete</a>',$_REQUEST['page'],'delete',$item['id']), ); //Return the title contents return sprintf('%1$s %2$s', /*$1%s*/ $item['email'], /*$2%s*/ $this->row_actions($actions) ); } function column_cb($item){ return sprintf( '<input type="checkbox" name="%1$s[]" value="%2$s" />', /*$1%s*/ $this->_args['singular'], /*$2%s*/ $item['id'] ); } function get_columns(){ $columns = array( 'cb' => '<input type="checkbox" />', //Render a checkbox instead of text 'email'=>__('Date'), 'date'=>__('Date'), 'common'=>__('Common Alert'), 'unit_id'=>__('Unique ID') ); return $columns; } public function get_sortable_columns() { $sortable_columns = array( 'email' => array('wp_user_id',false), //true means it's already sorted 'date' => array('date',false), 'common' => array('common',false) ); return $sortable_columns; } public function get_bulk_actions() { $actions = array( 'delete' => 'Delete', 'email' => 'Email' ); return $actions; } public function process_bulk_action() { global $wpdb; $notifications_tbl = $wpdb->prefix.'newsletter'; if( 'delete'===$this->current_action() ) { foreach($_POST['notification'] as $single_val){ $wpdb->delete( $notifications_tbl, array( 'id' => (int)$single_val ) ); } $redirect_url = get_admin_url( null, 'admin.php?page=subscribers' ); wp_safe_redirect($redirect_url); wp_die('Items deleted (or they would be if we had items to delete)!'); } if( 'email'===$this->current_action() ) { $result_email_ar = implode("-",$_POST['notification']); $redirect_url = get_admin_url( null, 'admin.php?page=kvcodes&ids='.$result_email_ar ); wp_safe_redirect($redirect_url); wp_die(' '); } } function prepare_items() { global $wpdb; //This is used only if making any database queries $database_name = $wpdb->prefix.'newsletter' ; $per_page = 10; $query = "SELECT * FROM $database_name ORDER BY id DESC"; $columns = $this->get_columns(); $hidden = array(); $sortable = $this->get_sortable_columns(); $this->_column_headers = array($columns, $hidden, $sortable); $this->process_bulk_action(); $data = $wpdb->get_results($query, ARRAY_A ); function usort_reorder($a,$b){ $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'title'; //If no sort, default to title $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc'; //If no order, default to asc $result = strcmp($a[$orderby], $b[$orderby]); //Determine sort order return ($order==='asc') ? $result : -$result; //Send final sort direction to usort } // usort($data, 'usort_reorder'); $current_page = $this->get_pagenum(); $total_items = count($data); $data = array_slice($data,(($current_page-1)*$per_page),$per_page); $this->items = $data; $this->set_pagination_args( array( 'total_items' => $total_items, //WE have to calculate the total number of items 'per_page' => $per_page, //WE have to determine how many items to show on a page 'total_pages' => ceil($total_items/$per_page) //WE have to calculate the total number of pages ) ); } }//class ``` and ``` echo '<form method="post">'; $mydownloads = new Kv_subscribers_list(); echo '</pre><div class="wrap"><h2>Subscribers<a href="'."http://".$_SERVER["SERVER_NAME"].$_SERVER['REQUEST_URI'].'&add_new=true" class="add-new-h2">Add New</a></h2>'; $mydownloads->prepare_items(); $mydownloads->display(); echo '</div></form>'; ``` Now, I want to make the filters like > > All || Published || Trash > > > I need to create a custom filter like this.
**Code** ``` class Kv_subscribers_list extends WP_List_Table { function __construct(){ global $status, $page; parent::__construct( array( 'singular' => 'notification', 'plural' => 'notifications', 'ajax' => false ) ); } protected function get_views() { $status_links = array( "all" => __("<a href='#'>All</a>",'my-plugin-slug'), "published" => __("<a href='#'>Published</a>",'my-plugin-slug'), "trashed" => __("<a href='#'>Trashed</a>",'my-plugin-slug') ); return $status_links; } function column_default($item, $column_name){ switch($column_name){ case 'email': case 'date': case 'common': case 'unit_id': return $item[$column_name]; default: return print_r($item,true); //Show the whole array for troubleshooting purposes } } function column_email($item){ $actions = array( 'email' => sprintf('<a href="?page=%s&action=%s&email_id=%s">E-mail</a>',$_REQUEST['page'],'email',$item['id']), 'delete' => sprintf('<a href="?page=%s&action=%s&delete_id=%s">Delete</a>',$_REQUEST['page'],'delete',$item['id']), ); //Return the title contents return sprintf('%1$s %2$s', /*$1%s*/ $item['email'], /*$2%s*/ $this->row_actions($actions) ); } function column_cb($item){ return sprintf( '<input type="checkbox" name="%1$s[]" value="%2$s" />', /*$1%s*/ $this->_args['singular'], /*$2%s*/ $item['id'] ); } function get_columns(){ $columns = array( 'cb' => '<input type="checkbox" />', 'email'=>__('Email'), 'date'=>__('Date'), 'common'=>__('Common Alert'), 'unit_id'=>__('Unique ID') ); return $columns; } public function get_sortable_columns() { $sortable_columns = array( 'email' => array('wp_user_id',false), //true means it's already sorted 'date' => array('date',false), 'common' => array('common',false) ); return $sortable_columns; } public function get_bulk_actions() { $actions = array( 'delete' => 'Delete', 'email' => 'Email' ); return $actions; } public function process_bulk_action() { global $wpdb; $notifications_tbl = $wpdb->prefix.'newsletter'; if( 'delete'===$this->current_action() ) { foreach($_POST['notification'] as $single_val){ $wpdb->delete( $notifications_tbl, array( 'id' => (int)$single_val ) ); } $redirect_url = get_admin_url( null, 'admin.php?page=subscribers' ); wp_safe_redirect($redirect_url); wp_die('Items deleted (or they would be if we had items to delete)!'); } if( 'email'===$this->current_action() ) { $result_email_ar = implode("-",$_POST['notification']); $redirect_url = get_admin_url( null, 'admin.php?page=kvcodes&ids='.$result_email_ar ); wp_safe_redirect($redirect_url); wp_die(' '); } } function prepare_items() { global $wpdb; //This is used only if making any database queries $database_name = $wpdb->prefix.'newsletter' ; $per_page = 10; $query = "SELECT * FROM $database_name ORDER BY id DESC"; $columns = $this->get_columns(); $hidden = array(); $sortable = $this->get_sortable_columns(); $this->_column_headers = array($columns, $hidden, $sortable); $this->process_bulk_action(); $data = $wpdb->get_results($query, ARRAY_A ); function usort_reorder($a,$b){ $orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'title'; //If no sort, default to title $order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc'; //If no order, default to asc $result = strcmp($a[$orderby], $b[$orderby]); //Determine sort order return ($order==='asc') ? $result : -$result; //Send final sort direction to usort } // usort($data, 'usort_reorder'); $current_page = $this->get_pagenum(); $total_items = count($data); $data = array_slice($data,(($current_page-1)*$per_page),$per_page); $this->items = $data; $this->set_pagination_args( array( 'total_items' => $total_items, //WE have to calculate the total number of items 'per_page' => $per_page, //WE have to determine how many items to show on a page 'total_pages' => ceil($total_items/$per_page) //WE have to calculate the total number of pages ) ); } }//class ``` **Admin Page & Rendering Sample** ``` function o_add_menu_items(){ add_menu_page('Plugin List Table', 'Sub', 'activate_plugins', 'subscribers', 'o_render_list_page'); } add_action('admin_menu', 'o_add_menu_items'); function o_render_list_page() { $mydownloads = new Kv_subscribers_list(); $title = __("Subscribers","my_plugin_slug"); ?> <div class="wrap"> <h1> <?php echo esc_html( $title );?> <!-- Check edit permissions --> <a href="<?php echo admin_url( 'admin.php?page=subscribers&add_new=true' ); ?>" class="page-title-action"> <?php echo esc_html_x('Add New', 'my-plugin-slug'); ?> </a> <?php ?> </h1> </div> <?php $mydownloads->views(); ?> <form method="post"> <?php $mydownloads->prepare_items(); $mydownloads->display(); ?> </form> <?php } ``` **Explanation** We need to override `WP_List_Table` class method [get\_views](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-list-table.php#L378) to get status links on the top.By default it is an empty array. [views](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-list-table.php#L388) method of `WP_List_Table` uses [get\_views](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-list-table.php#L378) to display list of those links that we return in the [get\_views](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-list-table.php#L378) as an associative array with separator `|`. We can also override [views](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-list-table.php#L388) method to have more control , for example if we want to change separator. Take a look at how other list tables are using that. For instance check [WP\_Posts\_List\_Table](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-posts-list-table.php#L264). After you have overridden the method then place `$mydownloads->views();` .be sure to escape all and internationalize strings. **Using Filter** We can use `views_{$this->screen->id}` filter once we have added [get\_views](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-admin/includes/class-wp-list-table.php#L378) method. Assuming `toplevel_page_subscribers` as screen id ``` add_filter('views_toplevel_page_subscribers','my_plugin_slug_status_links',10, 1); function my_plugin_slug_status_links($views) { $views['scheduled'] = "<a href='#'>Scheduled</a>"; return $views; } ```
223,604
<p>The wordpress built-in <strong>get_comments()</strong> can easily list out comments base on post type, post meta, post id or comment author id. But I would like to bring them togather, list out recent <strong>received</strong> comments from posts of specific author.</p> <p>My current way can only simply list all comments out:</p> <pre><code> &lt;?php $store_ID = $store_user-&gt;ID; $args = array( 'status' =&gt; 'approve', 'order' =&gt; 'DESC', 'orderby' =&gt; 'comment_date_gmt', 'meta_query' =&gt; array( array( 'key' =&gt; 'rating', 'value' =&gt; array(''), 'compare' =&gt; 'NOT IN' ) ) ); $comments = get_comments($args); if ( count( $comments ) == 0 ) { echo '&lt;span colspan="5"&gt;None message here&lt;/span&gt;'; } else {foreach ( $comments as $single_comment ) { echo 'loop content'; } ?&gt; </code></pre> <p>So I am looking for the part to specify the loop stay inside posts of sepcific author. May be some sql skills are needed?</p>
[ { "answer_id": 223899, "author": "marikamitsos", "author_id": 17797, "author_profile": "https://wordpress.stackexchange.com/users/17797", "pm_score": 2, "selected": true, "text": "<p>There are two commonly used mapping plugins for WordPress. For the next lines we assume you use the free <a href=\"https://wordpress.org/plugins/wordpress-mu-domain-mapping/\" rel=\"nofollow noreferrer\"><strong>WordPress MU Domain Mapping</strong></a> plugin from the WordPress plugin Repository.</p>\n\n<p>From your post I understand you have correctly mapped your domains (you have a dedicated IP or have already set-up the CNAMEs correctly).<br>\nYou have also correctly mapped your domains alpha.domain1.com to point to domain2.com and made domain2.com the primary domain.</p>\n\n<p><a href=\"https://i.stack.imgur.com/w2Te8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/w2Te8.png\" alt=\"mapping-01\"></a></p>\n\n<p>What you are asking for is possible. You just need to make the correct configuration. </p>\n\n<blockquote>\n <p>How to have the <strong>administration pages redirect to the mapped domain</strong>:</p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/XG5VD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XG5VD.png\" alt=\"mapping02\"></a></p>\n\n<ul>\n<li>Go to your \"<em>Network Settings</em>\" and click on \"<em>Domain Mapping</em>\". </li>\n<li>Check the two options as at the image above. You don't need to have anything else checked. </li>\n<li>Make sure you <strong>leave unchecked</strong> the\n\"<em>Redirect administration pages to network's original domain</em>\". </li>\n</ul>\n\n<p>If you read the <a href=\"https://wordpress.org/plugins/wordpress-mu-domain-mapping/installation/\" rel=\"nofollow noreferrer\">installation page</a>:</p>\n\n<blockquote>\n <ol start=\"4\">\n <li>\"Redirect administration pages to network's original domain (remote\n login disabled if this redirect is disabled)\" - with this checked, if\n a user visits their dashboard on a mapped domain it will redirect to\n the dashboard on the non mapped domain. If you don't want this, remote\n login will be disabled for security reasons.</li>\n </ol>\n</blockquote>\n\n<p>Do a <strong>final check</strong> by going to \"<em>Network Settings</em>\", \"<em>Sites</em>\", \"<em>Edit Site</em>\", \"<em>Settings</em>\".<br>\nMake sure both your \"<em>Siteurl</em>\" and \"<em>Home</em>\" fields point to your mapped domain.</p>\n\n<p><a href=\"https://i.stack.imgur.com/VUrPp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VUrPp.png\" alt=\"mapping-03\"></a></p>\n\n<p>The second mapping plugin is a paid one. You can find information on how to use it <a href=\"https://premium.wpmudev.org/project/domain-mapping/\" rel=\"nofollow noreferrer\">here</a>.<br>\nIf that is the one you use, under \"<em>Administration mapping</em>\" you should select \none of the two options provided. </p>\n\n<ul>\n<li>\"<em>domain entered by the user</em>\" gives the choice to the mapped site admin to point the administration area to either the mapped domain (domain2.com/wp-admin/) or the original domain (alpha.domain1.com/wp-admin/). </li>\n<li>\"<em>mapped domain</em>\" enables the access to the admin area through the mapped domain (domain2.com/wp-admin/).</li>\n</ul>\n" }, { "answer_id": 224037, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 0, "selected": false, "text": "<p>I think you need Domain Mapping. Domain mapping allows a blog on a multisite install to serve from any domain name. This way a blog does not have to be a subdirectory of the main install, or a subdomain. The WordPress Default supports Domain Mapping without Alias. Add the Domain in the blog-settings to the blog of the Network administration area.</p>\n\n<h3>Older Answers</h3>\n\n<p>If you have usaged the search on WPSE, maybe you found this helpful <a href=\"https://wordpress.stackexchange.com/questions/181914/what-is-the-correct-way-to-map-multiple-domains-in-a-wordpress-4-1-multisite-ins/182467#182467\">thread 182467</a>. Read it also, is much helpful.</p>\n\n<h2>Domain Setting with WP Core</h2>\n\n<p>You should add the domains to the site settings of each site in the Multisite.</p>\n\n<h3>Sites</h3>\n\n<p>See the follow example screenshot for a additional domain to other domain with directory structure.\n<a href=\"https://i.stack.imgur.com/TsnZk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TsnZk.png\" alt=\"enter image description here\"></a></p>\n\n<h3>Site Info, Domain Setting</h3>\n\n<p>To set a domain, edit the site-settings, tab \"Info\", also a screenshot, helps much more - I think.\n<a href=\"https://i.stack.imgur.com/hSiI6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hSiI6.png\" alt=\"enter image description here\"></a></p>\n\n<h3>Site Settings</h3>\n\n<p>Check also the settings, that the URL works for the site and the home-url.\n<a href=\"https://i.stack.imgur.com/HTQOL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HTQOL.png\" alt=\"enter image description here\"></a></p>\n\n<h2>Additional Hint</h2>\n\n<p>Often is it helpful - but not necessary, to set the <code>COOKIE_DOMAIN</code> constant to an empty string in your <code>wp-config.php</code>:</p>\n\n<pre><code>define( 'COOKIE_DOMAIN', '' );\n</code></pre>\n\n<p>Otherwise WordPress will always set it to your network's <code>$current_site-&gt;domain</code>, which could cause issues in some situations.</p>\n\n<h2>WordPress Core and Domain Alias</h2>\n\n<p>WordPress can handle different domains inside the core, no additional plugin is necessary. A plugin is only important, if you use alias of a domain. If you will use it, then you have two possibilities form ready usable plugins.</p>\n\n<ol>\n<li><a href=\"https://github.com/humanmade/Mercator\" rel=\"nofollow noreferrer\">Mercator - WordPress multisite domain mapping for the modern era.</a></li>\n<li><a href=\"https://wordpress.org/plugins/wordpress-mu-domain-mapping/\" rel=\"nofollow noreferrer\">WordPress MU Domain Mapping - Map any blog/site on a WordPressMU or WordPress 3.X network to an external domain.</a></li>\n</ol>\n" } ]
2016/04/13
[ "https://wordpress.stackexchange.com/questions/223604", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45717/" ]
The wordpress built-in **get\_comments()** can easily list out comments base on post type, post meta, post id or comment author id. But I would like to bring them togather, list out recent **received** comments from posts of specific author. My current way can only simply list all comments out: ``` <?php $store_ID = $store_user->ID; $args = array( 'status' => 'approve', 'order' => 'DESC', 'orderby' => 'comment_date_gmt', 'meta_query' => array( array( 'key' => 'rating', 'value' => array(''), 'compare' => 'NOT IN' ) ) ); $comments = get_comments($args); if ( count( $comments ) == 0 ) { echo '<span colspan="5">None message here</span>'; } else {foreach ( $comments as $single_comment ) { echo 'loop content'; } ?> ``` So I am looking for the part to specify the loop stay inside posts of sepcific author. May be some sql skills are needed?
There are two commonly used mapping plugins for WordPress. For the next lines we assume you use the free [**WordPress MU Domain Mapping**](https://wordpress.org/plugins/wordpress-mu-domain-mapping/) plugin from the WordPress plugin Repository. From your post I understand you have correctly mapped your domains (you have a dedicated IP or have already set-up the CNAMEs correctly). You have also correctly mapped your domains alpha.domain1.com to point to domain2.com and made domain2.com the primary domain. [![mapping-01](https://i.stack.imgur.com/w2Te8.png)](https://i.stack.imgur.com/w2Te8.png) What you are asking for is possible. You just need to make the correct configuration. > > How to have the **administration pages redirect to the mapped domain**: > > > [![mapping02](https://i.stack.imgur.com/XG5VD.png)](https://i.stack.imgur.com/XG5VD.png) * Go to your "*Network Settings*" and click on "*Domain Mapping*". * Check the two options as at the image above. You don't need to have anything else checked. * Make sure you **leave unchecked** the "*Redirect administration pages to network's original domain*". If you read the [installation page](https://wordpress.org/plugins/wordpress-mu-domain-mapping/installation/): > > 4. "Redirect administration pages to network's original domain (remote > login disabled if this redirect is disabled)" - with this checked, if > a user visits their dashboard on a mapped domain it will redirect to > the dashboard on the non mapped domain. If you don't want this, remote > login will be disabled for security reasons. > > > Do a **final check** by going to "*Network Settings*", "*Sites*", "*Edit Site*", "*Settings*". Make sure both your "*Siteurl*" and "*Home*" fields point to your mapped domain. [![mapping-03](https://i.stack.imgur.com/VUrPp.png)](https://i.stack.imgur.com/VUrPp.png) The second mapping plugin is a paid one. You can find information on how to use it [here](https://premium.wpmudev.org/project/domain-mapping/). If that is the one you use, under "*Administration mapping*" you should select one of the two options provided. * "*domain entered by the user*" gives the choice to the mapped site admin to point the administration area to either the mapped domain (domain2.com/wp-admin/) or the original domain (alpha.domain1.com/wp-admin/). * "*mapped domain*" enables the access to the admin area through the mapped domain (domain2.com/wp-admin/).
223,652
<p>I'm trying to remove two of the actions that adds a plugin (sportspress specifically). The actions of this plugins are:</p> <pre><code>add_action('sportspress_before_single_player','sportspress_output_player_details', 15); add_action('sportspress_single_player_content','sportspress_output_player_statistics',20); </code></pre> <p>I've created a plugin, and I want to remove these hooks, this is my code:</p> <pre><code>&lt;?php /* Plugin Name: my plugin Description: Plugin to override plugins' hooks Version: 0.1 Author: Company Name Author URI: http://www.example.com/ License: GPL2 */ add_action('plugins_loaded','remove_hooks'); function remove_hooks(){ remove_action( 'sportspress_before_single_player', 'sportspress_output_player_details' ); remove_action( 'sportspress_single_player_content', 'sportspress_output_player_statistics' ); } </code></pre> <p>I've searched and tried a lot of things, but I can't make it work.</p>
[ { "answer_id": 223655, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 2, "selected": false, "text": "<p>Plugins are loaded in the order of their file names. e.g. plugin with name <code>abc.php</code> loaded first then <code>xyz.php</code> so if you are trying to remove an action from plugin <code>abc.php</code> and that was added in plugin <code>xyz.php</code> then it is not possible without any tweak. Because action was never added at time you are trying to remove it.</p>\n\n<p>You can simply place a <code>die(__FILE__);</code> in both plugins to see which one echo the output first. If your plugin is loaded earlier than you can do two things to remove the action</p>\n\n<ol>\n<li>Rename your plugin and load it after actual plugin.</li>\n<li>I am not sure when parent actions run but there is a long list of actions <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow\">Action_Reference</a> on which you can hook remove action in your plugin. Now you know when to place <code>remove_action()</code> to make it effective.</li>\n</ol>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 240483, "author": "Brian Hellekin", "author_id": 94576, "author_profile": "https://wordpress.stackexchange.com/users/94576", "pm_score": 3, "selected": false, "text": "<p>I was with the same problem. I wanted to remove an action that comes from another plugin and replace it with another function I wrote in the plugin I was developing, but my file name (as @Sumit said) was after the original plugin file in alphabetical order. Even so I was been able to remove the action.</p>\n\n<p>What worked for me was wrapping my <code>remove_action</code> call inside another add_action to run it during after all plugin loading. That is possible by using the action <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/init\" rel=\"nofollow noreferrer\">init</a>:</p>\n\n<pre><code>add_action( 'init', 'changeActions' );\nfunction changeActions () {\n remove_action('my_action', 'the_function_from_the_plugin', 10);\n}\n</code></pre>\n\n<hr>\n\n<p>P.S.: If you want to see if the actions were properly removed, you can print somewhere the functions hooked to the action you want using the code from <a href=\"https://wordpress.stackexchange.com/a/216600\">this answer</a>. I used a test shortcode, since I was not working with the theme files (just add <code>[test_actions]</code> in any page inside the wordpress panel).</p>\n\n<pre><code>add_shortcode('test_actions', 'testActions');\nfunction testActions($attrs) {\n //get the list of all actions using this global variable\n global $wp_filter;\n\n //get only the actions hooked to 'my_action'\n $r = $wp_filter['my_action'];\n\n //return the array dump as a string\n return var_export($r, TRUE);\n}\n</code></pre>\n" }, { "answer_id": 256605, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 4, "selected": false, "text": "<p>There are two things that confuse people when trying to remove a hook:</p>\n\n<ol>\n<li>The <code>remove_action()</code> or <code>remove_filter()</code> calls must take place after the <code>add_action()</code> or <code>add_filter()</code> calls, <em>and</em> before the hook is actually fired. This means that you must know the hook when the calls were added <em>and</em> when the hook is fired.</li>\n<li>The <code>remove_action()</code> or <code>remove_filter()</code> calls must have the same priority as the <code>add_action()</code> or <code>add_filter()</code> call</li>\n</ol>\n\n<p>If these hooks were added on the init filter at the default priority, then to remove them, we'd simply hook into init at a priority later than 10 and remove them.</p>\n\n<pre><code>add_action( 'init', 'wpse_106269_remove_hooks', 11 );\nfunction wpse_106269_remove_hooks(){\n remove_action( 'sportspress_before_single_player', 'sportspress_output_player_details', 15 );\n remove_action( 'sportspress_single_player_content', 'sportspress_output_player_statistics', 20 );\n}\n</code></pre>\n\n<p>From <a href=\"https://codex.wordpress.org/Function_Reference/remove_action\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/remove_action</a></p>\n\n<blockquote>\n <p><strong><em>Important</strong>: To remove a hook, the $function_to_remove and $priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.</em></p>\n</blockquote>\n" } ]
2016/04/14
[ "https://wordpress.stackexchange.com/questions/223652", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92357/" ]
I'm trying to remove two of the actions that adds a plugin (sportspress specifically). The actions of this plugins are: ``` add_action('sportspress_before_single_player','sportspress_output_player_details', 15); add_action('sportspress_single_player_content','sportspress_output_player_statistics',20); ``` I've created a plugin, and I want to remove these hooks, this is my code: ``` <?php /* Plugin Name: my plugin Description: Plugin to override plugins' hooks Version: 0.1 Author: Company Name Author URI: http://www.example.com/ License: GPL2 */ add_action('plugins_loaded','remove_hooks'); function remove_hooks(){ remove_action( 'sportspress_before_single_player', 'sportspress_output_player_details' ); remove_action( 'sportspress_single_player_content', 'sportspress_output_player_statistics' ); } ``` I've searched and tried a lot of things, but I can't make it work.
There are two things that confuse people when trying to remove a hook: 1. The `remove_action()` or `remove_filter()` calls must take place after the `add_action()` or `add_filter()` calls, *and* before the hook is actually fired. This means that you must know the hook when the calls were added *and* when the hook is fired. 2. The `remove_action()` or `remove_filter()` calls must have the same priority as the `add_action()` or `add_filter()` call If these hooks were added on the init filter at the default priority, then to remove them, we'd simply hook into init at a priority later than 10 and remove them. ``` add_action( 'init', 'wpse_106269_remove_hooks', 11 ); function wpse_106269_remove_hooks(){ remove_action( 'sportspress_before_single_player', 'sportspress_output_player_details', 15 ); remove_action( 'sportspress_single_player_content', 'sportspress_output_player_statistics', 20 ); } ``` From <https://codex.wordpress.org/Function_Reference/remove_action> > > ***Important***: To remove a hook, the $function\_to\_remove and $priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure. > > >
223,654
<p>I don't know if this is the correct way to approach this, but here it goes. I'm working on Visual Composer (but could be vanilla WP), and I'm trying to implement a shortcode which generates another bunch of shortcodes. Somewhat a template shortcode.</p> <p>For example:</p> <pre><code>[test title="some title"] </code></pre> <p>Could be converted to:</p> <pre><code>[another_shortcode] [title]some title[/title] [get_posts total="5"] [/another_shortcode] </code></pre> <p>Which will be further processed until the HTML is generated.</p> <p>The thing that I'm trying to achieve is to tell the user to use some shortcodes which will generate a concrete Visual Composer shortcodes. This way I'm <strong>abstracting away the layout</strong> and if there are lot's of pages with a given layout they can be changed changing the shortcode.</p> <p>Does make any sense? Is it doable?</p>
[ { "answer_id": 223661, "author": "doup", "author_id": 91291, "author_profile": "https://wordpress.stackexchange.com/users/91291", "pm_score": 1, "selected": true, "text": "<p>Using <code>do_shortcode</code> within a shortcode does the trick of parsing the inner shortcodes. More information here: <a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/do_shortcode/</a></p>\n" }, { "answer_id": 223662, "author": "rmrol", "author_id": 92365, "author_profile": "https://wordpress.stackexchange.com/users/92365", "pm_score": -1, "selected": false, "text": "<p>Use do shortcode:</p>\n\n<pre><code>&lt;?php echo do_shortcode('[yourshortcode]'); ?&gt;\n</code></pre>\n" } ]
2016/04/14
[ "https://wordpress.stackexchange.com/questions/223654", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91291/" ]
I don't know if this is the correct way to approach this, but here it goes. I'm working on Visual Composer (but could be vanilla WP), and I'm trying to implement a shortcode which generates another bunch of shortcodes. Somewhat a template shortcode. For example: ``` [test title="some title"] ``` Could be converted to: ``` [another_shortcode] [title]some title[/title] [get_posts total="5"] [/another_shortcode] ``` Which will be further processed until the HTML is generated. The thing that I'm trying to achieve is to tell the user to use some shortcodes which will generate a concrete Visual Composer shortcodes. This way I'm **abstracting away the layout** and if there are lot's of pages with a given layout they can be changed changing the shortcode. Does make any sense? Is it doable?
Using `do_shortcode` within a shortcode does the trick of parsing the inner shortcodes. More information here: <https://developer.wordpress.org/reference/functions/do_shortcode/>
223,657
<p>I have pages, posts and woocommerce product categories and products in my website. I want to limit wordpress default search query so that it returns the posts, the pages, the product categories but <strong>NOT</strong> individual products. I am using the following code in my <code>functions.php</code> with which I can easily show only posts and pages. What I need now, is to show the woocommerce product categories along with my posts and pages in the search result, but <strong>NOT</strong> the individual products. Please help me out here.</p> <pre><code>function searchfilter($query) { if ($query-&gt;is_search &amp;&amp; !is_admin() ) { $query-&gt;set('post_type',array('post','page')); } return $query; } add_filter('pre_get_posts','searchfilter'); </code></pre>
[ { "answer_id": 223681, "author": "Monkey Puzzle", "author_id": 48568, "author_profile": "https://wordpress.stackexchange.com/users/48568", "pm_score": 3, "selected": true, "text": "<p>You may need to include a tax_query for the Woocommerce taxonomy (called 'product_cat'):</p>\n\n<pre><code> $tax_query = array(\n array(\n 'taxonomy' =&gt; 'product_cat'\n ),\n );\n $query-&gt;set( 'tax_query', $tax_query ); \n}\n\nreturn $query;\n}\n</code></pre>\n\n<p>However, you'll have to ensure that you can return posts AND pages AND product categories and also note the search results will be mixed up together.</p>\n\n<p>I would have thought a better solution, rather than filtering at functions.php level, would be to adapt your search.php for the display of the search results. You can then be quite targeted, for instance show:</p>\n\n<pre><code>Posts with this search include:\nPostX, PostY, PostZ.\n</code></pre>\n\n<p>And then another loop with:</p>\n\n<pre><code>Pages with this search include:\nPageA, PageB, PageC.\n</code></pre>\n\n<p>And then another loop with:</p>\n\n<pre><code>Product Categories with this search include:\nProduct Cat A, Product Cat F, Product Cat Z.\n</code></pre>\n\n<p>Is that the kind of result you are after, or would you like to filter EVERY search on your site and mix up the results?</p>\n" }, { "answer_id": 223705, "author": "Emin Özlem", "author_id": 74612, "author_profile": "https://wordpress.stackexchange.com/users/74612", "pm_score": 0, "selected": false, "text": "<pre><code>add_action('pre_get_posts','search_filter_exc_posts');\nfunction search_filter_exc_posts($query) {\n // Verify that we are on the search page &amp; this came from the search form\n if($query-&gt;query_vars['s'] != '' &amp;&amp; is_search())\n {\n $q_tax_query = $query-&gt;query_vars[\"tax_query\"];\n // append product categories to current tax query.\n $query-&gt;set('tax_query', $q_tax_query[]=array('taxonomy'=&gt;'product_cat') );\n }\n}\n</code></pre>\n" } ]
2016/04/14
[ "https://wordpress.stackexchange.com/questions/223657", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81686/" ]
I have pages, posts and woocommerce product categories and products in my website. I want to limit wordpress default search query so that it returns the posts, the pages, the product categories but **NOT** individual products. I am using the following code in my `functions.php` with which I can easily show only posts and pages. What I need now, is to show the woocommerce product categories along with my posts and pages in the search result, but **NOT** the individual products. Please help me out here. ``` function searchfilter($query) { if ($query->is_search && !is_admin() ) { $query->set('post_type',array('post','page')); } return $query; } add_filter('pre_get_posts','searchfilter'); ```
You may need to include a tax\_query for the Woocommerce taxonomy (called 'product\_cat'): ``` $tax_query = array( array( 'taxonomy' => 'product_cat' ), ); $query->set( 'tax_query', $tax_query ); } return $query; } ``` However, you'll have to ensure that you can return posts AND pages AND product categories and also note the search results will be mixed up together. I would have thought a better solution, rather than filtering at functions.php level, would be to adapt your search.php for the display of the search results. You can then be quite targeted, for instance show: ``` Posts with this search include: PostX, PostY, PostZ. ``` And then another loop with: ``` Pages with this search include: PageA, PageB, PageC. ``` And then another loop with: ``` Product Categories with this search include: Product Cat A, Product Cat F, Product Cat Z. ``` Is that the kind of result you are after, or would you like to filter EVERY search on your site and mix up the results?
223,658
<p>I have an image site which based on Wordpress. There are different resolutions below the picture in single post. For example:</p> <p>1024*768 - 1200*900 - 800*600</p> <p>When I click on one of these resolutions the image downloading directly to pc. Also creating these resolutions in wp-content/uploads folder. I want to remove one of these resolutions and add a custom dimension for uploads folder. How to make this please? Thanks.</p>
[ { "answer_id": 223681, "author": "Monkey Puzzle", "author_id": 48568, "author_profile": "https://wordpress.stackexchange.com/users/48568", "pm_score": 3, "selected": true, "text": "<p>You may need to include a tax_query for the Woocommerce taxonomy (called 'product_cat'):</p>\n\n<pre><code> $tax_query = array(\n array(\n 'taxonomy' =&gt; 'product_cat'\n ),\n );\n $query-&gt;set( 'tax_query', $tax_query ); \n}\n\nreturn $query;\n}\n</code></pre>\n\n<p>However, you'll have to ensure that you can return posts AND pages AND product categories and also note the search results will be mixed up together.</p>\n\n<p>I would have thought a better solution, rather than filtering at functions.php level, would be to adapt your search.php for the display of the search results. You can then be quite targeted, for instance show:</p>\n\n<pre><code>Posts with this search include:\nPostX, PostY, PostZ.\n</code></pre>\n\n<p>And then another loop with:</p>\n\n<pre><code>Pages with this search include:\nPageA, PageB, PageC.\n</code></pre>\n\n<p>And then another loop with:</p>\n\n<pre><code>Product Categories with this search include:\nProduct Cat A, Product Cat F, Product Cat Z.\n</code></pre>\n\n<p>Is that the kind of result you are after, or would you like to filter EVERY search on your site and mix up the results?</p>\n" }, { "answer_id": 223705, "author": "Emin Özlem", "author_id": 74612, "author_profile": "https://wordpress.stackexchange.com/users/74612", "pm_score": 0, "selected": false, "text": "<pre><code>add_action('pre_get_posts','search_filter_exc_posts');\nfunction search_filter_exc_posts($query) {\n // Verify that we are on the search page &amp; this came from the search form\n if($query-&gt;query_vars['s'] != '' &amp;&amp; is_search())\n {\n $q_tax_query = $query-&gt;query_vars[\"tax_query\"];\n // append product categories to current tax query.\n $query-&gt;set('tax_query', $q_tax_query[]=array('taxonomy'=&gt;'product_cat') );\n }\n}\n</code></pre>\n" } ]
2016/04/14
[ "https://wordpress.stackexchange.com/questions/223658", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92364/" ]
I have an image site which based on Wordpress. There are different resolutions below the picture in single post. For example: 1024\*768 - 1200\*900 - 800\*600 When I click on one of these resolutions the image downloading directly to pc. Also creating these resolutions in wp-content/uploads folder. I want to remove one of these resolutions and add a custom dimension for uploads folder. How to make this please? Thanks.
You may need to include a tax\_query for the Woocommerce taxonomy (called 'product\_cat'): ``` $tax_query = array( array( 'taxonomy' => 'product_cat' ), ); $query->set( 'tax_query', $tax_query ); } return $query; } ``` However, you'll have to ensure that you can return posts AND pages AND product categories and also note the search results will be mixed up together. I would have thought a better solution, rather than filtering at functions.php level, would be to adapt your search.php for the display of the search results. You can then be quite targeted, for instance show: ``` Posts with this search include: PostX, PostY, PostZ. ``` And then another loop with: ``` Pages with this search include: PageA, PageB, PageC. ``` And then another loop with: ``` Product Categories with this search include: Product Cat A, Product Cat F, Product Cat Z. ``` Is that the kind of result you are after, or would you like to filter EVERY search on your site and mix up the results?
223,684
<p>WP 4.5 introduced the <a href="https://wpsmackdown.com/device-preview-wordpress-customizer/" rel="nofollow noreferrer">Device Preview in the Customizer</a> and it's pretty easy to use. Click one of three icons and see your site at various (<em>predetermined</em>) sizes.</p> <ul> <li>The desktop version will always fill up 100% of your screen</li> <li>The tablet version is set to 6-inch x 9-inch</li> <li>The mobile version is set to 320px x 480px</li> </ul> <p>You can also filter the devices available or remove them alltogether using <a href="https://developer.wordpress.org/reference/hooks/customize_previewable_devices/" rel="nofollow noreferrer"><code>customize_previewable_devices</code></a></p> <pre><code>add_filter( 'customize_previewable_devices', '__return_empty_array' ); </code></pre> <p>There is a lot of discussion @<a href="https://core.trac.wordpress.org/ticket/31195" rel="nofollow noreferrer">#31195</a>, but assuming you can add/remove <a href="https://developer.wordpress.org/reference/classes/wp_customize_manager/get_previewable_devices/" rel="nofollow noreferrer">previewable devices</a> where do you determine the sizes for these views? </p> <p>For a reference on why more variety is better, please refer to <a href="http://design.google.com/resizer/" rel="nofollow noreferrer">http://design.google.com/resizer/</a>.</p> <h2>DEVICE ORIENTATION SOLUTION</h2> <p>Based on the answer by <a href="https://wordpress.stackexchange.com/a/224136/84219">Luis Sanz</a>, I think this solution is a bit more complete. It addresses adding new devices, setting icons, and adjusting the ordering of the devices in the list.</p> <p>While I think it's interesting to set the height of these windows to show the difference between portrait and landscape settings, I really think <code>100%</code> height is best for most cases.</p> <p>The icons are currently using <a href="http://developer.wordpress.org/resource/dashicons/" rel="nofollow noreferrer">Dashicons</a> but I could also see swapping these out for something that suggests breakpoints instead of devices down the road. <code>[SM, M, L, XL]</code></p> <pre><code>/** * Determine the device view size and icons in Customizer */ function wpse_20160503_adjust_customizer_responsive_sizes() { $mobile_margin_left = '-240px'; //Half of -$mobile_width $mobile_width = '480px'; $mobile_height = '720px'; $mobile_landscape_width = '720px'; $mobile_landscape_height = '480px'; $tablet_width = '720px'; $tablet_height = '1080px'; $tablet_landscape_width = '1080px'; $tablet_landscape_height = '720px'; ?&gt; &lt;style&gt; .wp-customizer .preview-mobile .wp-full-overlay-main { margin-left: &lt;?php echo $mobile_margin_left; ?&gt;; width: &lt;?php echo $mobile_width; ?&gt;; height: &lt;?php echo $mobile_height; ?&gt;; } .wp-customizer .preview-mobile-landscape .wp-full-overlay-main { width: &lt;?php echo $mobile_landscape_width; ?&gt;; height: &lt;?php echo $mobile_landscape_height; ?&gt;; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } .wp-customizer .preview-tablet .wp-full-overlay-main { width: &lt;?php echo $tablet_width; ?&gt;; height: &lt;?php echo $tablet_height; ?&gt;; } .wp-customizer .preview-tablet-landscape .wp-full-overlay-main { width: &lt;?php echo $tablet_landscape_width; ?&gt;; height: &lt;?php echo $tablet_landscape_height; ?&gt;; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } .wp-full-overlay-footer .devices .preview-tablet-landscape:before { content: "\f167"; } .wp-full-overlay-footer .devices .preview-mobile-landscape:before { content: "\f167"; } &lt;/style&gt; &lt;?php } add_action( 'customize_controls_print_styles', 'wpse_20160503_adjust_customizer_responsive_sizes' ); /** * Set device button settings and order */ function wpse_20160503_filter_customize_previewable_devices( $devices ) { $custom_devices[ 'desktop' ] = $devices[ 'desktop' ]; $custom_devices[ 'tablet' ] = $devices[ 'tablet' ]; $custom_devices[ 'tablet-landscape' ] = array ( 'label' =&gt; __( 'Enter tablet landscape preview mode' ), 'default' =&gt; false, ); $custom_devices[ 'mobile' ] = $devices[ 'mobile' ]; $custom_devices[ 'mobile-landscape' ] = array ( 'label' =&gt; __( 'Enter mobile landscape preview mode' ), 'default' =&gt; false, ); foreach ( $devices as $device =&gt; $settings ) { if ( ! isset( $custom_devices[ $device ] ) ) { $custom_devices[ $device ] = $settings; } } return $custom_devices; } add_filter( 'customize_previewable_devices', 'wpse_20160503_filter_customize_previewable_devices' ); </code></pre> <h2>MEDIA QUERY SOLUTION</h2> <p>Here is an example of utilizing break points like [<code>L|M|S</code>] based on the previous device orientation solution and without requiring extra glyphs. These should obviously compliment your theme's media queries.</p> <pre><code>/** * Determine the size of the devices and icons in Customizer */ function wpse_20160504_adjust_customizer_responsive_sizes() { ?&gt; &lt;style&gt; .wp-customizer .preview-small .wp-full-overlay-main { width: 320px; height: 100%; left: 50%; -webkit-transform: translateX(-50%); transform: translateX(-50%); } .wp-customizer .preview-medium .wp-full-overlay-main { width: 768px; height: 100%; left: 50%; -webkit-transform: translateX(-50%); transform: translateX(-50%); } .wp-customizer .preview-large .wp-full-overlay-main { width: 1224px; height: 100%; left: 50%; -webkit-transform: translateX(-50%); transform: translateX(-50%); } .wp-full-overlay-footer .devices .preview-small:before { content: "S"; } .wp-full-overlay-footer .devices .preview-medium:before { content: "M"; } .wp-full-overlay-footer .devices .preview-large:before { content: "L"; } &lt;/style&gt; &lt;?php } add_action( 'customize_controls_print_styles', 'wpse_20160504_adjust_customizer_responsive_sizes' ); /** * Add device sizes to customizer */ function wpse_20160504_filter_customize_previewable_devices( $devices ) { $custom_devices[ 'desktop' ] = $devices[ 'desktop' ]; $custom_devices[ 'large' ] = array ( 'label' =&gt; __( 'Large' ) ); $custom_devices[ 'medium' ] = array ( 'label' =&gt; __( 'Medium' ) ); $custom_devices[ 'small' ] = array ( 'label' =&gt; __( 'Small' ) ); return $custom_devices; } add_filter( 'customize_previewable_devices', 'wpse_20160504_filter_customize_previewable_devices' ); </code></pre>
[ { "answer_id": 224136, "author": "Luis Sanz", "author_id": 81084, "author_profile": "https://wordpress.stackexchange.com/users/81084", "pm_score": 3, "selected": true, "text": "<p>Both the mobile and the tablet dimensions are defined in the admin's <a href=\"https://core.trac.wordpress.org/browser/tags/4.5.1/src/wp-admin/css/themes.css#L1579\" rel=\"nofollow\">themes.css</a> file. The javascript that runs when the buttons are triggered is just for adding and removing classes and not for dealing with the sizes themselves.</p>\n\n<p>So it shouldn't be difficult to override the dimensions by adding some extra css. To keep it simple, I'm using <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/customize_controls_print_styles\" rel=\"nofollow\"><code>customize_controls_print_styles</code></a> to inline some styles but it can also be done by enqueueing a css file.</p>\n\n<pre><code>&lt;?php\n\n /*\n Plugin Name: Adjust Customizer responsive sizes\n Description: Allows to change the mobile and tablet preview dimensions in the WP Customizer\n Version: 0.1\n Author: Your Name\n Author URI: http://www.yourwebsite.com/\n */\n\n if ( ! defined( 'ABSPATH' ) ) exit;\n\n function wpse_223684_adjust_customizer_responsive_sizes() {\n\n $mobile_margin_left = '-240px'; //Half of -$mobile_width\n $mobile_width = '480px';\n $mobile_height = '720px';\n\n $tablet_margin_left = '-540px'; //Half of -$tablet_width\n $tablet_width = '1080px';\n $tablet_height = '720px';\n\n?&gt;\n &lt;style&gt;\n .wp-customizer .preview-mobile .wp-full-overlay-main {\n margin-left: &lt;?php echo $mobile_margin_left; ?&gt;;\n width: &lt;?php echo $mobile_width; ?&gt;;\n height: &lt;?php echo $mobile_height; ?&gt;;\n }\n\n .wp-customizer .preview-tablet .wp-full-overlay-main {\n margin-left: &lt;?php echo $tablet_margin_left; ?&gt;;\n width: &lt;?php echo $tablet_width; ?&gt;;\n height: &lt;?php echo $tablet_height; ?&gt;;\n }\n &lt;/style&gt;\n&lt;?php\n\n }\n\n add_action( 'customize_controls_print_styles', 'wpse_223684_adjust_customizer_responsive_sizes' );\n\n?&gt;\n</code></pre>\n\n<p>Default sizes are <code>320x480px</code> for mobile and <code>720x1080px</code> for tablet.</p>\n\n<p><strong>EDIT 16/04/26:</strong> Reflect the changes in the default tablet sizes the WordPress 4.5.1 release introduced.</p>\n" }, { "answer_id": 310781, "author": "Ben Matthews", "author_id": 127471, "author_profile": "https://wordpress.stackexchange.com/users/127471", "pm_score": 0, "selected": false, "text": "<p>A great solution by Luis Sanz. Worked great except for media queries that involve landscape and portrait queries as the iFrame doesn't scale. To get around this I used Luis' script and added</p>\n\n<pre><code>.wp-customizer .preview-tablet .wp-full-overlay-main iframe {\n height: &lt;?php echo $tablet_height; ?&gt; !important;\n}\n.wp-customizer .preview-mobile .wp-full-overlay-main iframe {\n height: &lt;?php echo $mobile_height; ?&gt; !important;\n}\n</code></pre>\n\n<p>I added this to the end of the section.</p>\n" } ]
2016/04/14
[ "https://wordpress.stackexchange.com/questions/223684", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84219/" ]
WP 4.5 introduced the [Device Preview in the Customizer](https://wpsmackdown.com/device-preview-wordpress-customizer/) and it's pretty easy to use. Click one of three icons and see your site at various (*predetermined*) sizes. * The desktop version will always fill up 100% of your screen * The tablet version is set to 6-inch x 9-inch * The mobile version is set to 320px x 480px You can also filter the devices available or remove them alltogether using [`customize_previewable_devices`](https://developer.wordpress.org/reference/hooks/customize_previewable_devices/) ``` add_filter( 'customize_previewable_devices', '__return_empty_array' ); ``` There is a lot of discussion @[#31195](https://core.trac.wordpress.org/ticket/31195), but assuming you can add/remove [previewable devices](https://developer.wordpress.org/reference/classes/wp_customize_manager/get_previewable_devices/) where do you determine the sizes for these views? For a reference on why more variety is better, please refer to <http://design.google.com/resizer/>. DEVICE ORIENTATION SOLUTION --------------------------- Based on the answer by [Luis Sanz](https://wordpress.stackexchange.com/a/224136/84219), I think this solution is a bit more complete. It addresses adding new devices, setting icons, and adjusting the ordering of the devices in the list. While I think it's interesting to set the height of these windows to show the difference between portrait and landscape settings, I really think `100%` height is best for most cases. The icons are currently using [Dashicons](http://developer.wordpress.org/resource/dashicons/) but I could also see swapping these out for something that suggests breakpoints instead of devices down the road. `[SM, M, L, XL]` ``` /** * Determine the device view size and icons in Customizer */ function wpse_20160503_adjust_customizer_responsive_sizes() { $mobile_margin_left = '-240px'; //Half of -$mobile_width $mobile_width = '480px'; $mobile_height = '720px'; $mobile_landscape_width = '720px'; $mobile_landscape_height = '480px'; $tablet_width = '720px'; $tablet_height = '1080px'; $tablet_landscape_width = '1080px'; $tablet_landscape_height = '720px'; ?> <style> .wp-customizer .preview-mobile .wp-full-overlay-main { margin-left: <?php echo $mobile_margin_left; ?>; width: <?php echo $mobile_width; ?>; height: <?php echo $mobile_height; ?>; } .wp-customizer .preview-mobile-landscape .wp-full-overlay-main { width: <?php echo $mobile_landscape_width; ?>; height: <?php echo $mobile_landscape_height; ?>; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } .wp-customizer .preview-tablet .wp-full-overlay-main { width: <?php echo $tablet_width; ?>; height: <?php echo $tablet_height; ?>; } .wp-customizer .preview-tablet-landscape .wp-full-overlay-main { width: <?php echo $tablet_landscape_width; ?>; height: <?php echo $tablet_landscape_height; ?>; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } .wp-full-overlay-footer .devices .preview-tablet-landscape:before { content: "\f167"; } .wp-full-overlay-footer .devices .preview-mobile-landscape:before { content: "\f167"; } </style> <?php } add_action( 'customize_controls_print_styles', 'wpse_20160503_adjust_customizer_responsive_sizes' ); /** * Set device button settings and order */ function wpse_20160503_filter_customize_previewable_devices( $devices ) { $custom_devices[ 'desktop' ] = $devices[ 'desktop' ]; $custom_devices[ 'tablet' ] = $devices[ 'tablet' ]; $custom_devices[ 'tablet-landscape' ] = array ( 'label' => __( 'Enter tablet landscape preview mode' ), 'default' => false, ); $custom_devices[ 'mobile' ] = $devices[ 'mobile' ]; $custom_devices[ 'mobile-landscape' ] = array ( 'label' => __( 'Enter mobile landscape preview mode' ), 'default' => false, ); foreach ( $devices as $device => $settings ) { if ( ! isset( $custom_devices[ $device ] ) ) { $custom_devices[ $device ] = $settings; } } return $custom_devices; } add_filter( 'customize_previewable_devices', 'wpse_20160503_filter_customize_previewable_devices' ); ``` MEDIA QUERY SOLUTION -------------------- Here is an example of utilizing break points like [`L|M|S`] based on the previous device orientation solution and without requiring extra glyphs. These should obviously compliment your theme's media queries. ``` /** * Determine the size of the devices and icons in Customizer */ function wpse_20160504_adjust_customizer_responsive_sizes() { ?> <style> .wp-customizer .preview-small .wp-full-overlay-main { width: 320px; height: 100%; left: 50%; -webkit-transform: translateX(-50%); transform: translateX(-50%); } .wp-customizer .preview-medium .wp-full-overlay-main { width: 768px; height: 100%; left: 50%; -webkit-transform: translateX(-50%); transform: translateX(-50%); } .wp-customizer .preview-large .wp-full-overlay-main { width: 1224px; height: 100%; left: 50%; -webkit-transform: translateX(-50%); transform: translateX(-50%); } .wp-full-overlay-footer .devices .preview-small:before { content: "S"; } .wp-full-overlay-footer .devices .preview-medium:before { content: "M"; } .wp-full-overlay-footer .devices .preview-large:before { content: "L"; } </style> <?php } add_action( 'customize_controls_print_styles', 'wpse_20160504_adjust_customizer_responsive_sizes' ); /** * Add device sizes to customizer */ function wpse_20160504_filter_customize_previewable_devices( $devices ) { $custom_devices[ 'desktop' ] = $devices[ 'desktop' ]; $custom_devices[ 'large' ] = array ( 'label' => __( 'Large' ) ); $custom_devices[ 'medium' ] = array ( 'label' => __( 'Medium' ) ); $custom_devices[ 'small' ] = array ( 'label' => __( 'Small' ) ); return $custom_devices; } add_filter( 'customize_previewable_devices', 'wpse_20160504_filter_customize_previewable_devices' ); ```
Both the mobile and the tablet dimensions are defined in the admin's [themes.css](https://core.trac.wordpress.org/browser/tags/4.5.1/src/wp-admin/css/themes.css#L1579) file. The javascript that runs when the buttons are triggered is just for adding and removing classes and not for dealing with the sizes themselves. So it shouldn't be difficult to override the dimensions by adding some extra css. To keep it simple, I'm using [`customize_controls_print_styles`](https://codex.wordpress.org/Plugin_API/Action_Reference/customize_controls_print_styles) to inline some styles but it can also be done by enqueueing a css file. ``` <?php /* Plugin Name: Adjust Customizer responsive sizes Description: Allows to change the mobile and tablet preview dimensions in the WP Customizer Version: 0.1 Author: Your Name Author URI: http://www.yourwebsite.com/ */ if ( ! defined( 'ABSPATH' ) ) exit; function wpse_223684_adjust_customizer_responsive_sizes() { $mobile_margin_left = '-240px'; //Half of -$mobile_width $mobile_width = '480px'; $mobile_height = '720px'; $tablet_margin_left = '-540px'; //Half of -$tablet_width $tablet_width = '1080px'; $tablet_height = '720px'; ?> <style> .wp-customizer .preview-mobile .wp-full-overlay-main { margin-left: <?php echo $mobile_margin_left; ?>; width: <?php echo $mobile_width; ?>; height: <?php echo $mobile_height; ?>; } .wp-customizer .preview-tablet .wp-full-overlay-main { margin-left: <?php echo $tablet_margin_left; ?>; width: <?php echo $tablet_width; ?>; height: <?php echo $tablet_height; ?>; } </style> <?php } add_action( 'customize_controls_print_styles', 'wpse_223684_adjust_customizer_responsive_sizes' ); ?> ``` Default sizes are `320x480px` for mobile and `720x1080px` for tablet. **EDIT 16/04/26:** Reflect the changes in the default tablet sizes the WordPress 4.5.1 release introduced.
223,707
<p>For <strong>multiple</strong> search terms; <code>?s=hello+world</code></p> <p>Wordpress work find <strong>"hello world"</strong> like <code>the_title</code> , <code>the_content</code> posts!</p> <ul> <li><em>And, if our post title <code>Hello Anna</code> wordpress does not get one results!</em></li> </ul> <blockquote> <p>I want to use all keys:</p> <p><strong>"hello world"</strong> , <strong>"hello"</strong> , <strong>"world"</strong></p> </blockquote> <p><strong>Maybe</strong> <code>array('hello world','hello','world');</code> but it exceeds my exp.! Is it in a single loop may be able to divide the query and send multiple queries? Is there someone who can help on the subject? <strong>e.g.</strong> <code>?s=</code>, <code>$_GET</code></p> <blockquote> <p>Wanted something must have been like to call more results for multiple queries!</p> </blockquote>
[ { "answer_id": 223709, "author": "1Bladesforhire", "author_id": 81382, "author_profile": "https://wordpress.stackexchange.com/users/81382", "pm_score": -1, "selected": false, "text": "<p>You are getting into deep water quickly. I would look into SearchWP plugin as they provide LIKE searching and Fuzzy matching. <a href=\"https://searchwp.com/\" rel=\"nofollow\">SearchWP</a></p>\n" }, { "answer_id": 223733, "author": "lllllllllllll", "author_id": 84842, "author_profile": "https://wordpress.stackexchange.com/users/84842", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Maybe somebody like me want <strong>fuzzy logic results</strong></p>\n</blockquote>\n\n<p>I solved this way: <strong>\"<code>search.php</code>\"</strong></p>\n\n<pre><code>&lt;?php\n $the_keys = preg_split('/\\s+/', get_query_var('s'),-1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);\n\n $total_keys = count($the_keys); // Count the search term\n\n $the_query = new WP_Query(array('s' =&gt; get_query_var('s')));\n\n // IF have multiple term and havent a result\n if($total_keys &gt; 1 &amp;&amp; $the_query-&gt;post_count &lt; 1){\n\n // Loop for total term count, if found post break it! &lt;3\n for($i = 0; $i &lt; $total_keys; $i++) {\n\n //Set the new array term value\n $the_query = new WP_Query(array('s' =&gt; $the_keys[$i]));\n\n //if found post break it! &lt;3\n if($the_query-&gt;post_count&gt;0) break;\n\n }\n\n }\n // List of my Level 2 filter posts :)\n if ($the_query-&gt;have_posts()) : ?&gt;\n\n......\n\n&lt;?php \nendwhile; \nendif; \n?&gt;\n</code></pre>\n\n<hr>\n\n<h2><strong>e.g.</strong> post title: ( <strong>Hello baby</strong> )</h2>\n\n<p>Normaly:</p>\n\n<ul>\n<li><code>?s=hello+baby</code> => <strong>find true</strong></li>\n<li><code>?s=hello</code> => <strong>find true</strong></li>\n<li><code>?s=baby</code> => <strong>find true</strong></li>\n<li><code>?s=hello+whats+up</code> => <strong>find false</strong></li>\n<li><code>?s=hey+baby</code> => <strong>find false</strong></li>\n</ul>\n\n<p>search, Work now and find <strong>e.g.</strong> <code>?s=hello+whats+up</code> => <strong>find true</strong></p>\n" }, { "answer_id": 223737, "author": "lllllllllllll", "author_id": 84842, "author_profile": "https://wordpress.stackexchange.com/users/84842", "pm_score": 3, "selected": true, "text": "<p>Fixed:\nSearch and result the all keys;</p>\n\n<pre><code> &lt;?php\n $the_keys = preg_split('/\\s+/', str_replace('-',' ',get_query_var('s')),-1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);\n $total_keys = count($the_keys);\n\n $the_query = new WP_Query(array('post_type'=&gt;'nothing'));\n\n if($total_keys&gt;1){\n\n for($i = 0; $i&lt;=$total_keys; $i++) {\n $the_query_mask = new WP_Query(array('s' =&gt; $the_keys[$i]));\n $the_query-&gt;post_count = count( $the_query-&gt;posts );\n $the_query-&gt;posts = array_merge( $the_query-&gt;posts, $the_query_mask-&gt;posts );\n } \n\n } else {\n\n $the_query= new WP_Query(array('s' =&gt; get_query_var('s')));\n\n }\n if ($the_query-&gt;have_posts()) : ?&gt;\n</code></pre>\n\n<p>Note: <strong><code>'post_type'=&gt;'nothing'</code></strong> just need array merge!</p>\n" } ]
2016/04/14
[ "https://wordpress.stackexchange.com/questions/223707", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84842/" ]
For **multiple** search terms; `?s=hello+world` Wordpress work find **"hello world"** like `the_title` , `the_content` posts! * *And, if our post title `Hello Anna` wordpress does not get one results!* > > I want to use all keys: > > > **"hello world"** , **"hello"** , **"world"** > > > **Maybe** `array('hello world','hello','world');` but it exceeds my exp.! Is it in a single loop may be able to divide the query and send multiple queries? Is there someone who can help on the subject? **e.g.** `?s=`, `$_GET` > > Wanted something must have been like to call more results for multiple queries! > > >
Fixed: Search and result the all keys; ``` <?php $the_keys = preg_split('/\s+/', str_replace('-',' ',get_query_var('s')),-1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $total_keys = count($the_keys); $the_query = new WP_Query(array('post_type'=>'nothing')); if($total_keys>1){ for($i = 0; $i<=$total_keys; $i++) { $the_query_mask = new WP_Query(array('s' => $the_keys[$i])); $the_query->post_count = count( $the_query->posts ); $the_query->posts = array_merge( $the_query->posts, $the_query_mask->posts ); } } else { $the_query= new WP_Query(array('s' => get_query_var('s'))); } if ($the_query->have_posts()) : ?> ``` Note: **`'post_type'=>'nothing'`** just need array merge!
223,708
<p>My site is <a href="http://exteriorinteriorsdesign.com/" rel="nofollow">http://exteriorinteriorsdesign.com/</a></p> <p>After Updating wordpress 4.5,it couldn't load my images and articles on Homepage, and dashboard also doesn't show when i move my cursor over there.</p> <p>Any solution?</p>
[ { "answer_id": 223712, "author": "Anthony", "author_id": 24924, "author_profile": "https://wordpress.stackexchange.com/users/24924", "pm_score": 0, "selected": false, "text": "<p>It's likely that it's a PHP error related to your template or a plugin, but you'll need more info to solve it. First try disable all plugins and see if that makes a difference.</p>\n\n<p>In order to see any errors that may be occurring, set your PHP <code>display_errors</code> directive to <code>On</code> if you have access, or you can try set the Debug constant in your Wordpress <code>wp-config.php</code> file to <code>true</code>. IE. <code>define( 'WP_DEBUG', true );</code></p>\n\n<p>If it is a PHP error, the instructions above will help you get more info on what the error is and where it's occurring.</p>\n" }, { "answer_id": 223713, "author": "Caspar", "author_id": 27191, "author_profile": "https://wordpress.stackexchange.com/users/27191", "pm_score": 3, "selected": false, "text": "<p>You are using a theme or plugin that uses a jQuery-dependent script with poor syntax. In this screenshot below of the browser console of the page you referenced, the expression should be <code>... li &gt; a[href*='#']</code>. Note the missing quotes around the #.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Drl75.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Drl75.png\" alt=\"Console screenshot of your site\"></a></p>\n\n<p>The bug didn't show up until now because WordPress 4.5 updated the version of jQuery it uses. The new jQuery version doesn't tolerate the bug. Ideally, your plugin/theme provider should issue a fix.</p>\n\n<p>Until then, you can get the old version of jQuery back by adding the following to your theme's <code>functions.php</code> file:</p>\n\n<pre><code>function wpse_use_previous_jquery() {\n if ( ! is_admin() ) {\n wp_deregister_script( 'jquery' );\n wp_register_script( 'jquery', 'https://code.jquery.com/jquery-1.11.3.min.js' );\n wp_enqueue_script( 'jquery' );\n }\n}\nadd_action( 'init', 'wpse_use_previous_jquery' );\n</code></pre>\n" } ]
2016/04/14
[ "https://wordpress.stackexchange.com/questions/223708", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92389/" ]
My site is <http://exteriorinteriorsdesign.com/> After Updating wordpress 4.5,it couldn't load my images and articles on Homepage, and dashboard also doesn't show when i move my cursor over there. Any solution?
You are using a theme or plugin that uses a jQuery-dependent script with poor syntax. In this screenshot below of the browser console of the page you referenced, the expression should be `... li > a[href*='#']`. Note the missing quotes around the #. [![Console screenshot of your site](https://i.stack.imgur.com/Drl75.png)](https://i.stack.imgur.com/Drl75.png) The bug didn't show up until now because WordPress 4.5 updated the version of jQuery it uses. The new jQuery version doesn't tolerate the bug. Ideally, your plugin/theme provider should issue a fix. Until then, you can get the old version of jQuery back by adding the following to your theme's `functions.php` file: ``` function wpse_use_previous_jquery() { if ( ! is_admin() ) { wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', 'https://code.jquery.com/jquery-1.11.3.min.js' ); wp_enqueue_script( 'jquery' ); } } add_action( 'init', 'wpse_use_previous_jquery' ); ```
223,722
<p>Updating to WordPress 4.5 broke my theme, <a href="http://emulate.themewoot.com/" rel="nofollow">ThemeWoot Emulate</a>. It appears that perhaps a stylesheet is somehow missing. Example symptoms:</p> <ul> <li>The mobile menu is shown by default</li> <li>The top search box is being shown by default</li> <li>The contact form modal is being shown by default</li> <li>Various links are underlined and a different font </li> </ul> <p>One thing I noticed was that, in the case where sections should be hidden by default, a <code>.hide</code> class is present, but there is no corresponding style being applied to that class. </p> <p>I tried clearing the server and browser cache. I've tried deactivating all plugins and updating them, but there's no difference. </p>
[ { "answer_id": 223723, "author": "Douglas Ludlow", "author_id": 12062, "author_profile": "https://wordpress.stackexchange.com/users/12062", "pm_score": 3, "selected": false, "text": "<p>It turns out that the ThemeWoot Emulate theme registers and enqueues a <code>common.css</code> file with the key of <code>common</code> in it's <code>themewoot.php</code> (which is being included in <code>functions.php</code>). </p>\n\n<p>This key is apparently conflicting with a wp-admin script being registered with the same <code>common</code> key, and so, instead of including Emulate's <code>common.css</code>, it's enqueuing and injecting the wp-admin <code>common.min.css</code>.</p>\n\n<p>I edited the <code>themewoot.php</code> and namespaced the <code>common</code> key with a an <code>emulate-</code> prefix:</p>\n\n<p><strong>From:</strong> </p>\n\n<pre><code>wp_register_style('common', $this-&gt;theme_url(). '/css/common.css', false, TWOOT_VERSION, 'all');\n\nwp_enqueue_style('common');\n</code></pre>\n\n<p><strong>To:</strong></p>\n\n<pre><code>wp_register_style('emulate-common', $this-&gt;theme_url(). '/css/common.css', false, TWOOT_VERSION, 'all');\n\nwp_enqueue_style('emulate-common');\n</code></pre>\n\n<p>And that got things back in working order.</p>\n\n<p>ThemeWoot <a href=\"http://themeforest.net/item/emulate-multipurpose-responsive-wordpress-theme/6058805\" rel=\"nofollow\">doesn't appear to be maintaining</a> the Emulate theme anymore. In reality they should patch this and provide an update.</p>\n\n<p><strong>&lt;rant&gt;</strong>\nWordPress should seriously consider namespacing their core styles and scripts so that updates don't affect themes like this. A simple <code>wp-</code> would have gone a long way here and saved me at least a few hours. Theme creators should also namespace all of their assets too so that they play nice with everything else.\n<strong>&lt;/rant&gt;</strong></p>\n" }, { "answer_id": 224033, "author": "Rudi", "author_id": 92566, "author_profile": "https://wordpress.stackexchange.com/users/92566", "pm_score": 0, "selected": false, "text": "<p>i have the same problem. The above fixed most of the theme styling however the portfolios and blog shortcodes and category pages are blank. They load the content and then it dissapears once the page fully loaded. Other style sheets maybe not loaded correctly to maybe? </p>\n" } ]
2016/04/14
[ "https://wordpress.stackexchange.com/questions/223722", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12062/" ]
Updating to WordPress 4.5 broke my theme, [ThemeWoot Emulate](http://emulate.themewoot.com/). It appears that perhaps a stylesheet is somehow missing. Example symptoms: * The mobile menu is shown by default * The top search box is being shown by default * The contact form modal is being shown by default * Various links are underlined and a different font One thing I noticed was that, in the case where sections should be hidden by default, a `.hide` class is present, but there is no corresponding style being applied to that class. I tried clearing the server and browser cache. I've tried deactivating all plugins and updating them, but there's no difference.
It turns out that the ThemeWoot Emulate theme registers and enqueues a `common.css` file with the key of `common` in it's `themewoot.php` (which is being included in `functions.php`). This key is apparently conflicting with a wp-admin script being registered with the same `common` key, and so, instead of including Emulate's `common.css`, it's enqueuing and injecting the wp-admin `common.min.css`. I edited the `themewoot.php` and namespaced the `common` key with a an `emulate-` prefix: **From:** ``` wp_register_style('common', $this->theme_url(). '/css/common.css', false, TWOOT_VERSION, 'all'); wp_enqueue_style('common'); ``` **To:** ``` wp_register_style('emulate-common', $this->theme_url(). '/css/common.css', false, TWOOT_VERSION, 'all'); wp_enqueue_style('emulate-common'); ``` And that got things back in working order. ThemeWoot [doesn't appear to be maintaining](http://themeforest.net/item/emulate-multipurpose-responsive-wordpress-theme/6058805) the Emulate theme anymore. In reality they should patch this and provide an update. **<rant>** WordPress should seriously consider namespacing their core styles and scripts so that updates don't affect themes like this. A simple `wp-` would have gone a long way here and saved me at least a few hours. Theme creators should also namespace all of their assets too so that they play nice with everything else. **</rant>**
223,757
<p>I want to use Wordpress REST API to Login and get user data on android app.</p> <p>I am using wp_users table for user and a custom table for user info .</p> <p>I tried writing my own REST API but i for that i have to make $wpdb accessible outside Wordpress installation. </p> <p>Please provide yours solution having API-KEY , or something similar , feature too.</p> <p>Thanks</p>
[ { "answer_id": 227127, "author": "Divyanshu Jimmy", "author_id": 92345, "author_profile": "https://wordpress.stackexchange.com/users/92345", "pm_score": 4, "selected": true, "text": "<p>I found the simplest solution using the WP-REST API plugin,first set this in yours environment :</p>\n\n<p>1.) In your themes <code>functions.php</code> register API endpoint hooks: </p>\n\n<pre><code>add_action( 'rest_api_init', 'register_api_hooks' );\n// API custom endpoints for WP-REST API\nfunction register_api_hooks() {\n\n register_rest_route(\n 'custom-plugin', '/login/',\n array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; 'login',\n )\n );\n\n function login() {\n\n $output = array();\n\n // Your logic goes here.\n return $output;\n\n }\n</code></pre>\n\n<p>2.) By default, if you have pretty permalinks enabled, the WordPress REST API “lives” at /wp-json/. Then the API endpoint is accessible at <code>youdomain.com/wp-json/custom-plugin/login</code> with a <code>POST</code> request.</p>\n\n<p>Notice that <strong>custom-plugin/login</strong> is actually defined in <strong>register_rest_route</strong> in PHP function <strong>register_api_hooks()</strong></p>\n\n<p>For API key I am using Wordpress Nonces - <a href=\"https://wordpress.stackexchange.com/q/223816/92345\">pretty straightforward as in my discussion here</a> . I hope these answers are useful for all full stack developers who are new to Wordpress REST API</p>\n" }, { "answer_id": 276680, "author": "Saran", "author_id": 25868, "author_profile": "https://wordpress.stackexchange.com/users/25868", "pm_score": 2, "selected": false, "text": "<p>If you just want to user login and get user details you can use and excellent plugin called \"JSON API AUTH\"</p>\n\n<p><a href=\"https://wordpress.org/plugins/json-api-auth/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/json-api-auth/</a></p>\n\n<p>There are following methods available: <code>validate_auth_cookie</code>, <code>generate_auth_cookie</code>, <code>clear_auth_cookie</code>, <code>get_currentuserinfo</code></p>\n\n<p>nonce can be created by calling <code>http://localhost/api/get_nonce/?controller=auth&amp;method=generate_auth_cookie</code></p>\n\n<p>You can then use ‘nonce’ value to generate cookie. <code>http://localhost/api/auth/generate_auth_cookie/?nonce=f4320f4a67&amp;username=Catherine&amp;password=password-here</code></p>\n\n<p>Use cookie like this with your other controller calls: <code>http://localhost/api/contoller-name/method-name/?cookie=Catherine|1392018917|3ad7b9f1c5c2cccb569c8a82119ca4fd</code></p>\n" } ]
2016/04/15
[ "https://wordpress.stackexchange.com/questions/223757", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92345/" ]
I want to use Wordpress REST API to Login and get user data on android app. I am using wp\_users table for user and a custom table for user info . I tried writing my own REST API but i for that i have to make $wpdb accessible outside Wordpress installation. Please provide yours solution having API-KEY , or something similar , feature too. Thanks
I found the simplest solution using the WP-REST API plugin,first set this in yours environment : 1.) In your themes `functions.php` register API endpoint hooks: ``` add_action( 'rest_api_init', 'register_api_hooks' ); // API custom endpoints for WP-REST API function register_api_hooks() { register_rest_route( 'custom-plugin', '/login/', array( 'methods' => 'POST', 'callback' => 'login', ) ); function login() { $output = array(); // Your logic goes here. return $output; } ``` 2.) By default, if you have pretty permalinks enabled, the WordPress REST API “lives” at /wp-json/. Then the API endpoint is accessible at `youdomain.com/wp-json/custom-plugin/login` with a `POST` request. Notice that **custom-plugin/login** is actually defined in **register\_rest\_route** in PHP function **register\_api\_hooks()** For API key I am using Wordpress Nonces - [pretty straightforward as in my discussion here](https://wordpress.stackexchange.com/q/223816/92345) . I hope these answers are useful for all full stack developers who are new to Wordpress REST API
223,764
<p>In wp-login.php default is:</p> <pre><code>&lt;meta name="robots" content="noindex,follow"&gt; </code></pre> <p>I want to change it to:</p> <pre><code>&lt;meta name="robots" content="noindex,nofollow"&gt; </code></pre> <p>Is there an easy way or script to change this?</p>
[ { "answer_id": 223772, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 2, "selected": false, "text": "<p>You can customize your WordPress login page with this action hook.</p>\n\n<pre><code>function f1() {\n echo '&lt;meta name=\"robots\" content=\"noindex,nofollow\" &gt;' . \"\\n\";\n}\nadd_action('login_head', 'f1');\n</code></pre>\n\n<p>The later one meta tag will prevail the original. PS. You can use filter if you plan to remove the original meta tag.</p>\n" }, { "answer_id": 223782, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 3, "selected": true, "text": "<p>Extending @prosti answer, WordPress add it using action <code>login_head</code> in <code>wp-login.php</code> itself.</p>\n\n<pre><code>add_action( 'login_head', 'wp_no_robots' );\n</code></pre>\n\n<p>You can remove this action in theme/plugin and add your own action with custom callback function.</p>\n\n<p>Example:-</p>\n\n<pre><code>//Keep priority 9 so we can remove WordPress action that is on 10\nadd_action( 'login_head', 'custom_no_robots', 9);\n/**\n * Custom robot tags\n */\nfunction custom_no_robots() {\n remove_action( 'login_head', 'wp_no_robots' );\n echo \"&lt;meta name='robots' content='noindex, nofollow' /&gt;\\n\";\n}\n</code></pre>\n" } ]
2016/04/15
[ "https://wordpress.stackexchange.com/questions/223764", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52641/" ]
In wp-login.php default is: ``` <meta name="robots" content="noindex,follow"> ``` I want to change it to: ``` <meta name="robots" content="noindex,nofollow"> ``` Is there an easy way or script to change this?
Extending @prosti answer, WordPress add it using action `login_head` in `wp-login.php` itself. ``` add_action( 'login_head', 'wp_no_robots' ); ``` You can remove this action in theme/plugin and add your own action with custom callback function. Example:- ``` //Keep priority 9 so we can remove WordPress action that is on 10 add_action( 'login_head', 'custom_no_robots', 9); /** * Custom robot tags */ function custom_no_robots() { remove_action( 'login_head', 'wp_no_robots' ); echo "<meta name='robots' content='noindex, nofollow' />\n"; } ```
223,770
<p>Is there any way to add a custom URL to the <code>wp_insert_post</code> function?</p> <pre><code>$my_post = array( 'post_title' =&gt; wp_strip_all_tags( $_POST['post_title'] ), 'post_content' =&gt; $_POST['post_content'], 'post_status' =&gt; 'publish', 'post_author' =&gt; 1, 'post_category' =&gt; array( 8,39 ) ); wp_insert_post( $my_post ); </code></pre>
[ { "answer_id": 223786, "author": "Caspar", "author_id": 27191, "author_profile": "https://wordpress.stackexchange.com/users/27191", "pm_score": -1, "selected": false, "text": "<p>Seems like you might be looking for this button:</p>\n\n<p><a href=\"https://i.stack.imgur.com/KUkhA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KUkhA.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 223787, "author": "Sasa1234", "author_id": 56652, "author_profile": "https://wordpress.stackexchange.com/users/56652", "pm_score": 2, "selected": true, "text": "<p>You can use <code>post_name</code> parameter.</p>\n\n<pre><code>$my_post = array(\n 'post_title' =&gt; wp_strip_all_tags( $_POST['post_title'] ),\n 'post_content' =&gt; $_POST['post_content'],\n 'post_status' =&gt; 'publish',\n 'post_author' =&gt; 1,\n 'post_category' =&gt; array( 8,39 ),\n 'post_name' =&gt; 'your-url'\n );\nwp_insert_post( $my_post );\n</code></pre>\n" } ]
2016/04/15
[ "https://wordpress.stackexchange.com/questions/223770", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92431/" ]
Is there any way to add a custom URL to the `wp_insert_post` function? ``` $my_post = array( 'post_title' => wp_strip_all_tags( $_POST['post_title'] ), 'post_content' => $_POST['post_content'], 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array( 8,39 ) ); wp_insert_post( $my_post ); ```
You can use `post_name` parameter. ``` $my_post = array( 'post_title' => wp_strip_all_tags( $_POST['post_title'] ), 'post_content' => $_POST['post_content'], 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array( 8,39 ), 'post_name' => 'your-url' ); wp_insert_post( $my_post ); ```
223,784
<p>I'm having an issue in WordPress where PHP is dying. I've increased memory, but the PHP process jumps to 100% CPU usage then dies and Apache throws a 500 error.</p> <p>I've tried to get Apache to log something, or PHP/MySQL to log an error but nothing is logged other then a general 500 error.</p> <p>The 500 issue is on the list page e.g.:</p> <pre><code>/wp-admin/edit.php?post_type=artist </code></pre> <p>We currently have over 1200 artist entries in WordPress, if I append a date sort like this:</p> <pre><code>/wp-admin/edit.php?post_type=artist&amp;orderby=date </code></pre> <p>Then the list loads up fine, fast even! I have sat and watched the MySQL query log and it appears that WordPress is loading up the meta data for every single post (all 1200 of them) in order to produce the list of 10 or so. For just one of the queries, that's returning 92000 rows. I'm using Advanced Custom Fields and a template with its own framework, so each post has a fair chunk of meta data attached. I'm thinking that this is too much data for PHP to process and I'm hitting a ceiling here. The 1200 posts is likely to double easily over the next year.</p> <p>How can I either force the initial page load to append the date sort or fix the issue with loading up all that meta data?</p>
[ { "answer_id": 229708, "author": "Paul Cullen", "author_id": 91132, "author_profile": "https://wordpress.stackexchange.com/users/91132", "pm_score": 0, "selected": false, "text": "<p>The problem was that the CPT was set to hierarchical, switching this to hierarchical: false in the functions.php resolved the problem.</p>\n" }, { "answer_id": 229875, "author": "locomo", "author_id": 42754, "author_profile": "https://wordpress.stackexchange.com/users/42754", "pm_score": 2, "selected": true, "text": "<p>Try changing <strong>hierarchical: false</strong> in your CPT definition (if your application allows).</p>\n\n<p>When CPT's are set to hierarchical: true all posts will be queried in the admin dashboard which can cause memory issues.</p>\n" } ]
2016/04/15
[ "https://wordpress.stackexchange.com/questions/223784", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91132/" ]
I'm having an issue in WordPress where PHP is dying. I've increased memory, but the PHP process jumps to 100% CPU usage then dies and Apache throws a 500 error. I've tried to get Apache to log something, or PHP/MySQL to log an error but nothing is logged other then a general 500 error. The 500 issue is on the list page e.g.: ``` /wp-admin/edit.php?post_type=artist ``` We currently have over 1200 artist entries in WordPress, if I append a date sort like this: ``` /wp-admin/edit.php?post_type=artist&orderby=date ``` Then the list loads up fine, fast even! I have sat and watched the MySQL query log and it appears that WordPress is loading up the meta data for every single post (all 1200 of them) in order to produce the list of 10 or so. For just one of the queries, that's returning 92000 rows. I'm using Advanced Custom Fields and a template with its own framework, so each post has a fair chunk of meta data attached. I'm thinking that this is too much data for PHP to process and I'm hitting a ceiling here. The 1200 posts is likely to double easily over the next year. How can I either force the initial page load to append the date sort or fix the issue with loading up all that meta data?
Try changing **hierarchical: false** in your CPT definition (if your application allows). When CPT's are set to hierarchical: true all posts will be queried in the admin dashboard which can cause memory issues.
223,871
<p>what I did: <li> I installed Wordpress on XAMPP</li> <li> Build a correctly working theme for Wordpress</li> <li> Copied this theme to another folder next to the first one in my Wordpress Themes-folder </li> <li> Made some css Changes and Changed some Header and Footer Tags </li> <li> When I now enable this newly created theme via WP-Admin panel and then try to access the initial page, I get an error that a connection to the server was not possible </li> <li> I found that the Apache has some problems when I try to load this second theme </li> <br/> Anybody an idea why Apache behaves like this and how to fix this?<br/> If any further info is need please just ask me. <br><br> EDIT 1: Thanks for answering Mark, unfortunately I already did look in the serverlogs. The serverlog shows that "Parent: child process exited with status 3221225725 -- Restarting." Google shows this error leads to a stack overflow connected to Windows machines. I then also added to the httpd.conf so that the maximum stack size was actully close to unreachable. Still I'm getting the same error. <br><br> Additionally, if I switch back to the first theme all the problems disappear. <br><br> I also tried a new installation of WordPress with this faulty theme and got the same problems. I'm going to check the debug log whether I find any hints there.<br> <br> EDIT 2: So now I set up WP_DEBUG and WP_DEBUG_LOG, unfortunately that doesn't help. The debug logfile in wp-content stays empty. No errors, warnings or notes. Seems like it is indeed an Apache / XAMPP problem. Going to dig in there a little deeper.<br> <br> EDIT 3: Eureka! I got close to the error. Seems like I messed up something in my functions.php.<br> <pre><code>/* * Load Scripts */ function wpbootstrap_scripts_with_jquery() { // Register the script like this for a theme: wp_register_script( 'customdrink', get_template_directory_uri() . '/js/customdrink.js', array( 'jquery','jquery-ui-slider' ) ); wp_register_script( 'jquery-ui-10', get_template_directory_uri() . '/js/jquery-ui-1.10.4.custom.min.js', array( 'jquery' ) ); wp_register_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.js', array( 'jquery' ) ); wp_register_script( 'awesome-landing-page', get_template_directory_uri() . '/js/awesome-landing-page.js', array( 'jquery', 'jquery-ui-10', 'boostrap' ) ); // For either a plugin or a theme, you can then enqueue the script: wp_enqueue_script( 'customdrink' ); wp_enqueue_script( 'jquery-ui-1.10' ); wp_enqueue_script( 'bootstrap' ); wp_enqueue_scripts( 'awesome-landing-page' ); } add_action( 'wp_enqueue_scripts', 'wpbootstrap_scripts_with_jquery' );</code></pre><br> I'm little unsure where I did go wrong here. Anybody an idea?</p>
[ { "answer_id": 229708, "author": "Paul Cullen", "author_id": 91132, "author_profile": "https://wordpress.stackexchange.com/users/91132", "pm_score": 0, "selected": false, "text": "<p>The problem was that the CPT was set to hierarchical, switching this to hierarchical: false in the functions.php resolved the problem.</p>\n" }, { "answer_id": 229875, "author": "locomo", "author_id": 42754, "author_profile": "https://wordpress.stackexchange.com/users/42754", "pm_score": 2, "selected": true, "text": "<p>Try changing <strong>hierarchical: false</strong> in your CPT definition (if your application allows).</p>\n\n<p>When CPT's are set to hierarchical: true all posts will be queried in the admin dashboard which can cause memory issues.</p>\n" } ]
2016/04/16
[ "https://wordpress.stackexchange.com/questions/223871", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91239/" ]
what I did: - I installed Wordpress on XAMPP - Build a correctly working theme for Wordpress - Copied this theme to another folder next to the first one in my Wordpress Themes-folder - Made some css Changes and Changed some Header and Footer Tags - When I now enable this newly created theme via WP-Admin panel and then try to access the initial page, I get an error that a connection to the server was not possible - I found that the Apache has some problems when I try to load this second theme Anybody an idea why Apache behaves like this and how to fix this? If any further info is need please just ask me. EDIT 1: Thanks for answering Mark, unfortunately I already did look in the serverlogs. The serverlog shows that "Parent: child process exited with status 3221225725 -- Restarting." Google shows this error leads to a stack overflow connected to Windows machines. I then also added to the httpd.conf so that the maximum stack size was actully close to unreachable. Still I'm getting the same error. Additionally, if I switch back to the first theme all the problems disappear. I also tried a new installation of WordPress with this faulty theme and got the same problems. I'm going to check the debug log whether I find any hints there. EDIT 2: So now I set up WP\_DEBUG and WP\_DEBUG\_LOG, unfortunately that doesn't help. The debug logfile in wp-content stays empty. No errors, warnings or notes. Seems like it is indeed an Apache / XAMPP problem. Going to dig in there a little deeper. EDIT 3: Eureka! I got close to the error. Seems like I messed up something in my functions.php. ``` /* * Load Scripts */ function wpbootstrap_scripts_with_jquery() { // Register the script like this for a theme: wp_register_script( 'customdrink', get_template_directory_uri() . '/js/customdrink.js', array( 'jquery','jquery-ui-slider' ) ); wp_register_script( 'jquery-ui-10', get_template_directory_uri() . '/js/jquery-ui-1.10.4.custom.min.js', array( 'jquery' ) ); wp_register_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.js', array( 'jquery' ) ); wp_register_script( 'awesome-landing-page', get_template_directory_uri() . '/js/awesome-landing-page.js', array( 'jquery', 'jquery-ui-10', 'boostrap' ) ); // For either a plugin or a theme, you can then enqueue the script: wp_enqueue_script( 'customdrink' ); wp_enqueue_script( 'jquery-ui-1.10' ); wp_enqueue_script( 'bootstrap' ); wp_enqueue_scripts( 'awesome-landing-page' ); } add_action( 'wp_enqueue_scripts', 'wpbootstrap_scripts_with_jquery' ); ``` I'm little unsure where I did go wrong here. Anybody an idea?
Try changing **hierarchical: false** in your CPT definition (if your application allows). When CPT's are set to hierarchical: true all posts will be queried in the admin dashboard which can cause memory issues.
223,885
<p>I'm currently trying to setup a custom nav walker that will use container_class from the menu as a prefix for the class names of the list items and children.</p> <pre><code>$defaults = array( 'menu' =&gt; '', 'menu_class' =&gt; '', 'menu_id' =&gt; '', 'container' =&gt; 'nav', 'container_class' =&gt; 'nav-primary', 'container_id' =&gt; '', 'before' =&gt; '', 'after' =&gt; '', 'link_before' =&gt; '', 'link_after' =&gt; '', 'depth' =&gt; 0, 'walker' =&gt; new Custom_Nav_Walker(), 'theme_location' =&gt; 'primary', 'items_wrap' =&gt; '&lt;ul&gt;%3$s&lt;/ul&gt;', ); wp_nav_menu( $defaults ); </code></pre> <p>The general idea is the walker will loop out the classes according to the container class name. Like so.</p> <pre><code>&lt;nav class="nav-primary"&gt; &lt;li class="nav-primary__item"&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li class="nav-primary__item"&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li class="nav-primary__item"&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;/nav&gt; </code></pre> <p>Hopefully someone can help. </p>
[ { "answer_id": 223886, "author": "550", "author_id": 92492, "author_profile": "https://wordpress.stackexchange.com/users/92492", "pm_score": 0, "selected": false, "text": "<p>So far i've tried pulling the value from the nav template. </p>\n\n<p><a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/nav-menu-template.php\" rel=\"nofollow\">https://github.com/WordPress/WordPress/blob/master/wp-includes/nav-menu-template.php</a>. </p>\n\n<p>I know it's related to<br>\n<code>$class = $args-&gt;container_class ? ' class=\"' . esc_attr( $args-&gt;container_class ) . '\"' : ' class=\"menu-'. $menu-&gt;slug .'-container\"'; on line 353.</code></p>\n\n<p>The value returns null when requesting it. The idea is to loop the value out as part of the class name. As I only need to return the name itself.</p>\n\n<pre><code>'primary-menu__item'\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>$container_class . '-menu__item\n</code></pre>\n" }, { "answer_id": 223887, "author": "Tung Du", "author_id": 83304, "author_profile": "https://wordpress.stackexchange.com/users/83304", "pm_score": 2, "selected": true, "text": "<p>Go with a custom Walker</p>\n\n<pre><code>class Your_Walker_Nav_Menu extends Walker_Nav_Menu {\n var $container_class;\n public function __construct($container_class) {\n $this-&gt;container_class = $container_class;\n }\n\n function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n global $wp_query;\n $indent = ( $depth &gt; 0 ? str_repeat( \"\\t\", $depth ) : '' ); // code indent\n\n // Depth-dependent classes.\n $depth_classes = array(\n ( $depth == 0 ? 'main-menu-item' : 'sub-menu-item' ),\n ( $depth &gt;=2 ? 'sub-sub-menu-item' : '' ),\n ( $depth % 2 ? 'menu-item-odd' : 'menu-item-even' ),\n 'menu-item-depth-' . $depth\n );\n $depth_class_names = esc_attr( implode( ' ', $depth_classes ) );\n\n // Passed classes.\n $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;\n $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );\n\n // Build HTML.\n $output .= $indent . '&lt;li id=\"nav-menu-item-'. $item-&gt;ID . '\" class=\"'. $this-&gt;container_class . '__item ' . $depth_class_names . ' ' . $class_names . '\"&gt;';\n\n // Link attributes.\n $attributes = ! empty( $item-&gt;attr_title ) ? ' title=\"' . esc_attr( $item-&gt;attr_title ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;target ) ? ' target=\"' . esc_attr( $item-&gt;target ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;xfn ) ? ' rel=\"' . esc_attr( $item-&gt;xfn ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;url ) ? ' href=\"' . esc_attr( $item-&gt;url ) .'\"' : '';\n $attributes .= ' class=\"menu-link ' . ( $depth &gt; 0 ? 'sub-menu-link' : 'main-menu-link' ) . '\"';\n\n // Build HTML output and pass through the proper filter.\n $item_output = sprintf( '%1$s&lt;a%2$s&gt;%3$s%4$s%5$s&lt;/a&gt;%6$s',\n $args-&gt;before,\n $attributes,\n $args-&gt;link_before,\n apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ),\n $args-&gt;link_after,\n $args-&gt;after\n );\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n }\n}\n</code></pre>\n\n<p>Notice the construct function, then when you call the menu:</p>\n\n<pre><code>'container_class' =&gt; 'nav-primary',\n'walker' =&gt; new Your_Walker_Nav_Menu('nav-primary')\n</code></pre>\n" } ]
2016/04/16
[ "https://wordpress.stackexchange.com/questions/223885", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92492/" ]
I'm currently trying to setup a custom nav walker that will use container\_class from the menu as a prefix for the class names of the list items and children. ``` $defaults = array( 'menu' => '', 'menu_class' => '', 'menu_id' => '', 'container' => 'nav', 'container_class' => 'nav-primary', 'container_id' => '', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'depth' => 0, 'walker' => new Custom_Nav_Walker(), 'theme_location' => 'primary', 'items_wrap' => '<ul>%3$s</ul>', ); wp_nav_menu( $defaults ); ``` The general idea is the walker will loop out the classes according to the container class name. Like so. ``` <nav class="nav-primary"> <li class="nav-primary__item"><a href="#">Link</a></li> <li class="nav-primary__item"><a href="#">Link</a></li> <li class="nav-primary__item"><a href="#">Link</a></li> </nav> ``` Hopefully someone can help.
Go with a custom Walker ``` class Your_Walker_Nav_Menu extends Walker_Nav_Menu { var $container_class; public function __construct($container_class) { $this->container_class = $container_class; } function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { global $wp_query; $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent // Depth-dependent classes. $depth_classes = array( ( $depth == 0 ? 'main-menu-item' : 'sub-menu-item' ), ( $depth >=2 ? 'sub-sub-menu-item' : '' ), ( $depth % 2 ? 'menu-item-odd' : 'menu-item-even' ), 'menu-item-depth-' . $depth ); $depth_class_names = esc_attr( implode( ' ', $depth_classes ) ); // Passed classes. $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); // Build HTML. $output .= $indent . '<li id="nav-menu-item-'. $item->ID . '" class="'. $this->container_class . '__item ' . $depth_class_names . ' ' . $class_names . '">'; // Link attributes. $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $attributes .= ' class="menu-link ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"'; // Build HTML output and pass through the proper filter. $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s', $args->before, $attributes, $args->link_before, apply_filters( 'the_title', $item->title, $item->ID ), $args->link_after, $args->after ); $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } ``` Notice the construct function, then when you call the menu: ``` 'container_class' => 'nav-primary', 'walker' => new Your_Walker_Nav_Menu('nav-primary') ```
223,897
<p>I'm inserting an image in my theme as follows:</p> <pre><code>the_post_thumbnail('large'); </code></pre> <p>Which results in the following HTML:</p> <pre><code>&lt;img class="wp-post-image" width="660" height="440" sizes="(max-width: 660px) 100vw, 660px" srcset="/uploads/IMG-1024x683.jpg 1024w, /uploads/IMG-300x200.jpg 300w, /uploads/IMG-768x512.jpg 768w, /uploads/IMG-254x169.jpg 254w, /uploads/IMG-578x385.jpg 578w, /uploads/IMG-665x443.jpg 665w, /uploads/IMG-1600x1067.jpg 1600w" src="/uploads/IMG-1024x683.jpg"&gt; </code></pre> <p>Notice <code>width="660" height="440"</code> and <code>sizes="(max-width: 660px) 100vw, 660px"</code> which doesn't correlate with the size defined for <code>large</code> in Media Settings > Image sizes which is supposed to be 1024 x 1024.</p> <p>What am I doing wrong?</p>
[ { "answer_id": 223901, "author": "Tung Du", "author_id": 83304, "author_profile": "https://wordpress.stackexchange.com/users/83304", "pm_score": 0, "selected": false, "text": "<p>You're doing right. Just miss one step. I guess you upload image before change the size of large in setting. Final step is Regenerated thumbnail. Just install the plugin with same name, go to Tool > Regenerate thumbnail and click. ;)</p>\n" }, { "answer_id": 223915, "author": "wpclevel", "author_id": 92212, "author_profile": "https://wordpress.stackexchange.com/users/92212", "pm_score": 3, "selected": false, "text": "<p>WordPress uses <code>min( intval($content_width), $max_width )</code> inside <code>image_constrain_size_for_editor</code> for <code>large</code> image size.</p>\n\n<p>As I can see your <code>$content_width</code> is set to 660. So, change the <code>$content_width</code> in your <code>functions.php</code> file to the <code>1024</code> or whatever you need. For full-width layout, it's better to remove it.</p>\n\n<p>Example: <code>$GLOBALS['content_width'] = 1600</code>. That's it.</p>\n\n<p>If you don't know what <code>content_width</code> is, see <strong><a href=\"https://codex.wordpress.org/Content_Width\">Content Width</a></strong> for more info.</p>\n" }, { "answer_id": 224044, "author": "Narek Zakarian", "author_id": 92573, "author_profile": "https://wordpress.stackexchange.com/users/92573", "pm_score": 0, "selected": false, "text": "<p>try this way </p>\n\n<pre><code>$image = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), 'large', false);\n\n\n&lt;img src=\"&lt;?php echo esc_url($image[0]);?&gt;\" alt=\"\"&gt;\n</code></pre>\n" } ]
2016/04/17
[ "https://wordpress.stackexchange.com/questions/223897", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80625/" ]
I'm inserting an image in my theme as follows: ``` the_post_thumbnail('large'); ``` Which results in the following HTML: ``` <img class="wp-post-image" width="660" height="440" sizes="(max-width: 660px) 100vw, 660px" srcset="/uploads/IMG-1024x683.jpg 1024w, /uploads/IMG-300x200.jpg 300w, /uploads/IMG-768x512.jpg 768w, /uploads/IMG-254x169.jpg 254w, /uploads/IMG-578x385.jpg 578w, /uploads/IMG-665x443.jpg 665w, /uploads/IMG-1600x1067.jpg 1600w" src="/uploads/IMG-1024x683.jpg"> ``` Notice `width="660" height="440"` and `sizes="(max-width: 660px) 100vw, 660px"` which doesn't correlate with the size defined for `large` in Media Settings > Image sizes which is supposed to be 1024 x 1024. What am I doing wrong?
WordPress uses `min( intval($content_width), $max_width )` inside `image_constrain_size_for_editor` for `large` image size. As I can see your `$content_width` is set to 660. So, change the `$content_width` in your `functions.php` file to the `1024` or whatever you need. For full-width layout, it's better to remove it. Example: `$GLOBALS['content_width'] = 1600`. That's it. If you don't know what `content_width` is, see **[Content Width](https://codex.wordpress.org/Content_Width)** for more info.
223,904
<p>Hi I'm fairly new to Shortcode programming and was wondering if it is possible to process the following nested shortcode with different shortcode tags:</p> <pre><code>[review] [title]Sample Review[/title] [image]http://localhost/wordpress/wp-content/uploads/2016/04/picture.jpg[/image] [criteria title="Criteria 1" score="100"] [criteria title="Criteria 2" score="90"] [criteria title="Criteria 3" score="80"] [/review] </code></pre> <p>To produce this intended html block:</p> <pre><code>&lt;section id="review"&gt; &lt;div class="review-top"&gt; &lt;h2&gt;Sample Review&lt;/h2&gt; &lt;!--Content of [title][/title]--&gt; &lt;/div&gt; &lt;div class="review-left"&gt; &lt;img src="http://localhost/wordpress/wp-content/uploads/2016/04/picture.jpg"&gt; &lt;!--Content of [image][/image]--&gt; &lt;/div&gt; &lt;div class="review-criteria"&gt; &lt;h3&gt;Criteria 1 - 100&lt;/h3&gt; &lt;!--Attribute of [criteria]--&gt; &lt;/div&gt; &lt;div class="review-criteria"&gt; &lt;h3&gt;Criteria 2 - 90&lt;/h3&gt; &lt;!--Attribute of [criteria]--&gt; &lt;/div&gt; &lt;div class="review-criteria"&gt; &lt;h3&gt;Criteria 3 - 80&lt;/h3&gt; &lt;!--Attribute of [criteria]--&gt; &lt;/div&gt; &lt;div class="review-summary"&gt; &lt;h2&gt;90&lt;/h2&gt; &lt;!--Average of Criteria 1-3's score--&gt; &lt;/div&gt; &lt;/section&gt; </code></pre> <p>I understand I have to use recursively use do_shortcodes($content) but doing so will call all the shortcodes from $contents and will produce the following:</p> <pre><code>&lt;section id="review"&gt; &lt;div class="review-top"&gt; &lt;h2&gt;Sample Review&lt;/h2&gt; &lt;!--Content of [title][/title]--&gt; &lt;img src="http://localhost/wordpress/wp-content/uploads/2016/04/picture.jpg"&gt; &lt;!--Content of [image][/image]--&gt; &lt;div class="review-criteria"&gt; &lt;h3&gt;Criteria 1 - 100&lt;/h3&gt; &lt;!--Attribute of [criteria]--&gt; &lt;/div&gt; &lt;div class="review-criteria"&gt; &lt;h3&gt;Criteria 2 - 90&lt;/h3&gt; &lt;!--Attribute of [criteria]--&gt; &lt;/div&gt; &lt;div class="review-criteria"&gt; &lt;h3&gt;Criteria 3 - 80&lt;/h3&gt; &lt;!--Attribute of [criteria]--&gt; &lt;/div&gt; &lt;/div&gt; ... &lt;/section&gt; </code></pre> <p>Shortcodes is the following:</p> <pre><code>function makeTitle( $atts, $content = null ) { return '&lt;h2&gt;'.$content. '&lt;/h2&gt; &lt;!--Content of [title][/title]--&gt;'; } add_shortcode('title', 'makeTitle'); function makeImage( $atts, $content = null ) { return '&lt;img src="'.$content.'"&gt; &lt;!--Content of [image][/image]--&gt;'; } add_shortcode('image', 'makeImage'); function makeCriteria( $atts, $content = null ) { extract(shortcode_atts( array( 'title' =&gt; 'Criteria', 'score' =&gt; '0', ), $atts )); return '&lt;div class="review-criteria"&gt; &lt;h3&gt;'.$title. ' - ' .$score. '&lt;/h3&gt; &lt;!--Attribute of [criteria]--&gt; &lt;/div&gt;'; } add_shortcode('criteria', 'makeCriteria'); function makeReview( $atts , $content = null ) { return '&lt;section id="review"&gt;&lt;div class="review-top"&gt;'.do_shortcode($content).'&lt;/div&gt;&lt;/section&gt;'; ... } add_shortcode('review', 'makeReview'); </code></pre> <p>What I wanted to happen is on the first do_shortcode($content) it should only do_shortcode for [title][/title]. Thank you very much!</p>
[ { "answer_id": 223901, "author": "Tung Du", "author_id": 83304, "author_profile": "https://wordpress.stackexchange.com/users/83304", "pm_score": 0, "selected": false, "text": "<p>You're doing right. Just miss one step. I guess you upload image before change the size of large in setting. Final step is Regenerated thumbnail. Just install the plugin with same name, go to Tool > Regenerate thumbnail and click. ;)</p>\n" }, { "answer_id": 223915, "author": "wpclevel", "author_id": 92212, "author_profile": "https://wordpress.stackexchange.com/users/92212", "pm_score": 3, "selected": false, "text": "<p>WordPress uses <code>min( intval($content_width), $max_width )</code> inside <code>image_constrain_size_for_editor</code> for <code>large</code> image size.</p>\n\n<p>As I can see your <code>$content_width</code> is set to 660. So, change the <code>$content_width</code> in your <code>functions.php</code> file to the <code>1024</code> or whatever you need. For full-width layout, it's better to remove it.</p>\n\n<p>Example: <code>$GLOBALS['content_width'] = 1600</code>. That's it.</p>\n\n<p>If you don't know what <code>content_width</code> is, see <strong><a href=\"https://codex.wordpress.org/Content_Width\">Content Width</a></strong> for more info.</p>\n" }, { "answer_id": 224044, "author": "Narek Zakarian", "author_id": 92573, "author_profile": "https://wordpress.stackexchange.com/users/92573", "pm_score": 0, "selected": false, "text": "<p>try this way </p>\n\n<pre><code>$image = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), 'large', false);\n\n\n&lt;img src=\"&lt;?php echo esc_url($image[0]);?&gt;\" alt=\"\"&gt;\n</code></pre>\n" } ]
2016/04/17
[ "https://wordpress.stackexchange.com/questions/223904", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92497/" ]
Hi I'm fairly new to Shortcode programming and was wondering if it is possible to process the following nested shortcode with different shortcode tags: ``` [review] [title]Sample Review[/title] [image]http://localhost/wordpress/wp-content/uploads/2016/04/picture.jpg[/image] [criteria title="Criteria 1" score="100"] [criteria title="Criteria 2" score="90"] [criteria title="Criteria 3" score="80"] [/review] ``` To produce this intended html block: ``` <section id="review"> <div class="review-top"> <h2>Sample Review</h2> <!--Content of [title][/title]--> </div> <div class="review-left"> <img src="http://localhost/wordpress/wp-content/uploads/2016/04/picture.jpg"> <!--Content of [image][/image]--> </div> <div class="review-criteria"> <h3>Criteria 1 - 100</h3> <!--Attribute of [criteria]--> </div> <div class="review-criteria"> <h3>Criteria 2 - 90</h3> <!--Attribute of [criteria]--> </div> <div class="review-criteria"> <h3>Criteria 3 - 80</h3> <!--Attribute of [criteria]--> </div> <div class="review-summary"> <h2>90</h2> <!--Average of Criteria 1-3's score--> </div> </section> ``` I understand I have to use recursively use do\_shortcodes($content) but doing so will call all the shortcodes from $contents and will produce the following: ``` <section id="review"> <div class="review-top"> <h2>Sample Review</h2> <!--Content of [title][/title]--> <img src="http://localhost/wordpress/wp-content/uploads/2016/04/picture.jpg"> <!--Content of [image][/image]--> <div class="review-criteria"> <h3>Criteria 1 - 100</h3> <!--Attribute of [criteria]--> </div> <div class="review-criteria"> <h3>Criteria 2 - 90</h3> <!--Attribute of [criteria]--> </div> <div class="review-criteria"> <h3>Criteria 3 - 80</h3> <!--Attribute of [criteria]--> </div> </div> ... </section> ``` Shortcodes is the following: ``` function makeTitle( $atts, $content = null ) { return '<h2>'.$content. '</h2> <!--Content of [title][/title]-->'; } add_shortcode('title', 'makeTitle'); function makeImage( $atts, $content = null ) { return '<img src="'.$content.'"> <!--Content of [image][/image]-->'; } add_shortcode('image', 'makeImage'); function makeCriteria( $atts, $content = null ) { extract(shortcode_atts( array( 'title' => 'Criteria', 'score' => '0', ), $atts )); return '<div class="review-criteria"> <h3>'.$title. ' - ' .$score. '</h3> <!--Attribute of [criteria]--> </div>'; } add_shortcode('criteria', 'makeCriteria'); function makeReview( $atts , $content = null ) { return '<section id="review"><div class="review-top">'.do_shortcode($content).'</div></section>'; ... } add_shortcode('review', 'makeReview'); ``` What I wanted to happen is on the first do\_shortcode($content) it should only do\_shortcode for [title][/title]. Thank you very much!
WordPress uses `min( intval($content_width), $max_width )` inside `image_constrain_size_for_editor` for `large` image size. As I can see your `$content_width` is set to 660. So, change the `$content_width` in your `functions.php` file to the `1024` or whatever you need. For full-width layout, it's better to remove it. Example: `$GLOBALS['content_width'] = 1600`. That's it. If you don't know what `content_width` is, see **[Content Width](https://codex.wordpress.org/Content_Width)** for more info.
223,917
<p>I have a website running the Photocrati theme version 4.9.3 on an AWS t2.micro running Amazon Linux. I use PHP 5.6 with php-fpm and a very recent version of Nginx, compiled with a couple of modules. I have CloudFlare in front of the website, but it accepts connections only from CloudFlare not directly.</p> <p>One Wordpress 4.5 site running Photocrati keeps going down, because for some reason the siteurl in the wp_options table keeps getting changed to </p> <pre><code>https://www.example.com/wp-login.php/wp-content/themes/photocrati-theme/styles/wp-admin/wp-admin/wp-admin/wp-content/themes/photocrati-theme/styles/wp-admin/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles </code></pre> <p>I can fix it with the SQL below, but it's annoying, causing downtime. I've scripted this so cron runs it every five minutes - obviously this isn't a great solution, but it will do until I can get it fixed properly.</p> <pre><code>update wp_options set option_value = "https://www.example.com/" where option_id = 1 </code></pre> <p>I have three other sites on the same server that are fine. None run photocrati - they run a variety of other themes. As far as I'm aware nothing has changed that recently - I switched from Nginx to PHP 5.6 around a week ago, but this started happening 3-5 days after I made that change. All the sites run the same plugins, listed below. I've set up the MySQL query log on RDS, maybe that'll give me a hint.</p> <pre><code>Akismet CloudFlare Contact Form 7 Contact Form DB Google Analytics by MonsterInsights (it just changed its name to this) Remove query strings from static resources Ultimate Nofollow UpdraftPlus - Backup/Restore Yeost SEO </code></pre> <p>Photocrati support replied and said they don't know what's going on.</p> <p>I've done site security scans with securi (plugin and website) and Wordfence. No issues found.</p> <p>File permissions are all set as restrictive as I can get away with while still allowing auto updates and plugin/theme installs via the web ui. I can see the SQL being executed in the database, when I look for anything malicious in the access log there's nothing significant there - an innocuous query hitting a category of the blog.</p> <p>Has anyone seen anything similar? Any suggestions how to fix the underlying issue? How do I even track this one down? I need to work out which line of code is running that query.</p> <p><strong>To be clear</strong> - I can bring the site up when it goes down very easily, I'd really appreciate help working out why it's happening. I'm an ex enterprize developer so I'm fairly technical, I've been using Wordpress for quite a few years, I'm good with it - I just don't develop for it so I don't really know the problem.</p> <p>Note that I posted this question on this site first, but someone told me this site isn't for support. I posted it on Server Fault and they moved it back here.</p>
[ { "answer_id": 223918, "author": "RRikesh", "author_id": 17305, "author_profile": "https://wordpress.stackexchange.com/users/17305", "pm_score": 0, "selected": false, "text": "<p>I think you messed up the value. <code>home</code> and <code>siteurl</code> values should not end up with a slash.</p>\n\n<p>A better query (assuming WP is in the root directory) would be:</p>\n\n<pre><code>UPDATE wp_options\nSET options_value = 'https://www.example.com'\nWHERE option_name IN ('home','siteurl');\n</code></pre>\n" }, { "answer_id": 223965, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": true, "text": "<p>If this is done via WP Options API (as opposed to direct SQL query on database) you can use hooks to log it.</p>\n\n<p>Something along the lines of (not tested, make sure it works under normal option save first):</p>\n\n<pre><code>add_filter( 'pre_update_option_siteurl', function ( $value ) {\n\n error_log( wp_debug_backtrace_summary() );\n\n return $value;\n} );\n</code></pre>\n\n<p>Next time it happens you should get much better idea about underlying reason from the backtrace.</p>\n\n<p>Until you got it fixed you could also hardcode this into configuration to prevent breakage itself:</p>\n\n<pre><code>define('WP_HOME','http://example.com');\ndefine('WP_SITEURL','http://example.com');\n</code></pre>\n" } ]
2016/04/17
[ "https://wordpress.stackexchange.com/questions/223917", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92467/" ]
I have a website running the Photocrati theme version 4.9.3 on an AWS t2.micro running Amazon Linux. I use PHP 5.6 with php-fpm and a very recent version of Nginx, compiled with a couple of modules. I have CloudFlare in front of the website, but it accepts connections only from CloudFlare not directly. One Wordpress 4.5 site running Photocrati keeps going down, because for some reason the siteurl in the wp\_options table keeps getting changed to ``` https://www.example.com/wp-login.php/wp-content/themes/photocrati-theme/styles/wp-admin/wp-admin/wp-admin/wp-content/themes/photocrati-theme/styles/wp-admin/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles/wp-content/themes/photocrati-theme/styles ``` I can fix it with the SQL below, but it's annoying, causing downtime. I've scripted this so cron runs it every five minutes - obviously this isn't a great solution, but it will do until I can get it fixed properly. ``` update wp_options set option_value = "https://www.example.com/" where option_id = 1 ``` I have three other sites on the same server that are fine. None run photocrati - they run a variety of other themes. As far as I'm aware nothing has changed that recently - I switched from Nginx to PHP 5.6 around a week ago, but this started happening 3-5 days after I made that change. All the sites run the same plugins, listed below. I've set up the MySQL query log on RDS, maybe that'll give me a hint. ``` Akismet CloudFlare Contact Form 7 Contact Form DB Google Analytics by MonsterInsights (it just changed its name to this) Remove query strings from static resources Ultimate Nofollow UpdraftPlus - Backup/Restore Yeost SEO ``` Photocrati support replied and said they don't know what's going on. I've done site security scans with securi (plugin and website) and Wordfence. No issues found. File permissions are all set as restrictive as I can get away with while still allowing auto updates and plugin/theme installs via the web ui. I can see the SQL being executed in the database, when I look for anything malicious in the access log there's nothing significant there - an innocuous query hitting a category of the blog. Has anyone seen anything similar? Any suggestions how to fix the underlying issue? How do I even track this one down? I need to work out which line of code is running that query. **To be clear** - I can bring the site up when it goes down very easily, I'd really appreciate help working out why it's happening. I'm an ex enterprize developer so I'm fairly technical, I've been using Wordpress for quite a few years, I'm good with it - I just don't develop for it so I don't really know the problem. Note that I posted this question on this site first, but someone told me this site isn't for support. I posted it on Server Fault and they moved it back here.
If this is done via WP Options API (as opposed to direct SQL query on database) you can use hooks to log it. Something along the lines of (not tested, make sure it works under normal option save first): ``` add_filter( 'pre_update_option_siteurl', function ( $value ) { error_log( wp_debug_backtrace_summary() ); return $value; } ); ``` Next time it happens you should get much better idea about underlying reason from the backtrace. Until you got it fixed you could also hardcode this into configuration to prevent breakage itself: ``` define('WP_HOME','http://example.com'); define('WP_SITEURL','http://example.com'); ```
223,929
<p>I have basically worked on this all night and I realize I am quite stuck. </p> <p>I have a sidebar in my wordpress theme that displays the most recent posts. The sidebar looks like this:</p> <p><a href="https://i.stack.imgur.com/yI9ZJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yI9ZJ.png" alt="enter image description here"></a></p> <p>Below each title I want to display the post date in "relative style" e.g "posted two days ago".</p> <p>I know <code>&lt;?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?&gt;</code> will produce the relative date but I do not know how to implement this in the same code I already have.</p> <p>I also need to be able to style this date stamp with custom CSS.</p> <p><strong>This is the php I have for the sidebar:</strong></p> <pre><code>&lt;?php $args = array( 'post_status' =&gt; 'publish', 'numberposts' =&gt; '30', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'post_format', 'field' =&gt; 'slug', 'terms' =&gt; 'post-format-aside', 'operator' =&gt; 'NOT IN' ), array( 'taxonomy' =&gt; 'post_format', 'field' =&gt; 'slug', 'terms' =&gt; 'post-format-image', 'operator' =&gt; 'NOT IN' ) ) ); $recent_posts = wp_get_recent_posts( $args ); foreach( $recent_posts as $recent ){ echo '&lt;div class="sidebar-entries"&gt;'; echo get_the_post_thumbnail( $recent['ID'], 'sidebar-thumb', array( 'class' =&gt; 'sidebar-image' ) ); echo '&lt;div class="sidebar-entries-title"&gt;'; echo '&lt;a href="' . get_permalink($recent["ID"]) . '"&gt;' . ( __($recent["post_title"])).'&lt;/a&gt;&lt;/div&gt;&lt;/div&gt; '; // echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; } ?&gt; </code></pre>
[ { "answer_id": 223923, "author": "wpclevel", "author_id": 92212, "author_profile": "https://wordpress.stackexchange.com/users/92212", "pm_score": 3, "selected": true, "text": "<p>You can get it easily by making a GET request to: <a href=\"http://yourdomain.com/wp-json/\" rel=\"nofollow\">http://yourdomain.com/wp-json/</a>. You will see your site name, description, url and home...</p>\n" }, { "answer_id": 314767, "author": "basil", "author_id": 94636, "author_profile": "https://wordpress.stackexchange.com/users/94636", "pm_score": 0, "selected": false, "text": "<p>I recommend <a href=\"https://wordpress.org/plugins/wp-rest-jmespath/\" rel=\"nofollow noreferrer\">WP REST JMESPath</a> for fields filtering and other output modifications.</p>\n\n<p>Example: <code>/wp-json/wp/v2/pages?_query=[0:2].{id: id, title: title.rendered}</code> means get last two pages; get id field; transform title.rendered --> title</p>\n\n<p>Kilo bytes not problem for nowadays internet, but such JSON filtering can be applied to other rest queries. </p>\n\n<p>Also, such filtered response can be passed directly to React component as props without messing existing component props.</p>\n" } ]
2016/04/17
[ "https://wordpress.stackexchange.com/questions/223929", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82313/" ]
I have basically worked on this all night and I realize I am quite stuck. I have a sidebar in my wordpress theme that displays the most recent posts. The sidebar looks like this: [![enter image description here](https://i.stack.imgur.com/yI9ZJ.png)](https://i.stack.imgur.com/yI9ZJ.png) Below each title I want to display the post date in "relative style" e.g "posted two days ago". I know `<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?>` will produce the relative date but I do not know how to implement this in the same code I already have. I also need to be able to style this date stamp with custom CSS. **This is the php I have for the sidebar:** ``` <?php $args = array( 'post_status' => 'publish', 'numberposts' => '30', 'tax_query' => array( array( 'taxonomy' => 'post_format', 'field' => 'slug', 'terms' => 'post-format-aside', 'operator' => 'NOT IN' ), array( 'taxonomy' => 'post_format', 'field' => 'slug', 'terms' => 'post-format-image', 'operator' => 'NOT IN' ) ) ); $recent_posts = wp_get_recent_posts( $args ); foreach( $recent_posts as $recent ){ echo '<div class="sidebar-entries">'; echo get_the_post_thumbnail( $recent['ID'], 'sidebar-thumb', array( 'class' => 'sidebar-image' ) ); echo '<div class="sidebar-entries-title">'; echo '<a href="' . get_permalink($recent["ID"]) . '">' . ( __($recent["post_title"])).'</a></div></div> '; // echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; } ?> ```
You can get it easily by making a GET request to: <http://yourdomain.com/wp-json/>. You will see your site name, description, url and home...
223,975
<p>I'm making a custom post meta search with the pre_get_posts function in my Divi child theme functions.php file. The problem is that the final query gathers not only the results for my custom post field (named 'autor') but other fields like 'post_title' and 'post_post' which I have not included.</p> <p>That's the resulting query with the troublesome line highlighted in strong:</p> <p>SELECT SQL_CALC_FOUND_ROWS ebj_posts.ID FROM ebj_posts INNER JOIN ebj_term_relationships ON (ebj_posts.ID = ebj_term_relationships.object_id) INNER JOIN ebj_postmeta ON ( ebj_posts.ID = ebj_postmeta.post_id ) INNER JOIN ebj_postmeta AS mt1 ON ( ebj_posts.ID = mt1.post_id ) WHERE 1=1 AND ( ebj_term_relationships.term_taxonomy_id IN (456) ) <strong>AND (((ebj_posts.post_title LIKE '%Abulafia%') OR (ebj_posts.post_content LIKE '%Abulafia%')))</strong> AND ( ebj_postmeta.meta_key = 'autor' AND ( ( mt1.meta_key = 'autor' AND CAST(mt1.meta_value AS CHAR) LIKE '%Abulafia%' ) ) ) AND ebj_posts.post_type IN ('post', 'page', 'attachment', 'project', 'ref_bib') AND ((ebj_posts.post_status = 'publish')) GROUP BY ebj_posts.ID ORDER BY ebj_postmeta.meta_value ASC LIMIT 0, 30"</p> <p>As you can see the word 'Abulafia' is searched in the <strong>post_title</strong> and <strong>post_content</strong> fields, which is not intended.</p> <p>This line in bold with the AND arguments come from WP > wp-includes > query line 2196:</p> <pre><code>$search .= $wpdb-&gt;prepare( "{$searchand}(($wpdb-&gt;posts.post_title $like_op %s) $andor_op ($wpdb-&gt;posts.post_content $like_op %s))", $like, $like ); </code></pre> <p>because when I comment these line in the wordpress core code the problem vanish.</p> <p>That's my code in functions.php:</p> <pre><code>function filtra_inici( $query ){ global $wp; if ( ( is_archive() ) &amp;&amp; $query-&gt;is_main_query() &amp;&amp; !is_admin() ) { if ($query-&gt;is_search &amp;&amp; isset($_GET['search-type']) &amp;&amp; $_GET['search-type'] == 'autor') { $query-&gt;set( 'post_type', 'ref_bib'); $query-&gt;set( 'post_status', 'publish'); $query-&gt;set( 'orderby', 'meta_value'); $query-&gt;set( 'meta_key', 'autor' ); $query-&gt;set( 'order', 'ASC' ); $meta_query = array('relation' =&gt; 'AND'); array_push( $meta_query, array( 'key' =&gt; 'autor', 'value' =&gt; $query-&gt;query_vars['s'], 'compare' =&gt; 'LIKE' )); $query-&gt;set( 'meta_query', $meta_query); } }// end is_archive } </code></pre> <p>Thanks!</p>
[ { "answer_id": 223983, "author": "Joel", "author_id": 65652, "author_profile": "https://wordpress.stackexchange.com/users/65652", "pm_score": 0, "selected": false, "text": "<p>The parameter for meta query is meta_key, not just key (according to <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/WP_Query</a>)</p>\n\n<p>Try 'meta_key' => 'autor' instead of 'key' => 'autor' </p>\n" }, { "answer_id": 224001, "author": "user5200704", "author_id": 92477, "author_profile": "https://wordpress.stackexchange.com/users/92477", "pm_score": 2, "selected": false, "text": "<p>Create a another filter to remove post title and post content remove search terms \ntry this if this helpful for you</p>\n\n<pre><code>add_filter( 'posts_search', 'custom_post_search_author_do', 10, 2 );\n\nfunction custom_post_search_author_do($search, $query ){\n if( ! empty($search) \n &amp;&amp; $query-&gt;is_main_query() \n &amp;&amp; !is_admin() \n &amp;&amp; isset($_GET['search-type'])\n &amp;&amp; $_GET['search-type'] == 'autor'\n )\n $search = '';\n return $search;\n}\n</code></pre>\n" }, { "answer_id": 224086, "author": "Xavier Caliz", "author_id": 65514, "author_profile": "https://wordpress.stackexchange.com/users/65514", "pm_score": 1, "selected": false, "text": "<h1>SOLVED!</h1>\n\n<p>In response to @tomjnowell : Yep! you are right, I'm not giving enough details nor context, sorry. I'm not used to post questions here, nor the english is my mother tongue, as you can see. So thanks to be so patient as to help me.</p>\n\n<h2>What I wanted</h2>\n\n<p>What I intended is to make a search by several post meta AND, optionally, ALL the post meta PLUS the post_title in a custom post type called ref_bib.</p>\n\n<p>You can see the thing in action in <a href=\"http://www.elsborja.cat/cat_bib/general/\" rel=\"nofollow\">this site</a> about <a href=\"http://www.elsborja.cat/cat_bib/general/\" rel=\"nofollow\">the Borgia family</a> (mainly in catalan).</p>\n\n<p>As you'll notice, initially there is several forms: the first to perform a general search (in custom post meta and post_title) and four more for the rest of options (yes, you are right: it can be simplified. I'll do).</p>\n\n<p>Actually thanks to user5200704 I've made some research here and there and found finally something which is working pretty well for me (though not in a total and exhilarating happiness, as I'll probably explain in another question).</p>\n\n<h2>What I've got</h2>\n\n<p>In case somebody is interested, here is the code.</p>\n\n<p>That's the search form (there is one for each post meta in the first version of the code, later I'll use a dropdown to make it sexier) :</p>\n\n<pre><code>&lt;form method=\"get\" id=\"searchform\" class=\"searchform\" action=\"http://www.elsborja.cat/cat_bib/general/\"&gt;\n&lt;div class=\"cercadiv\"&gt;\n&lt;input type=\"text\" value=\"\" name=\"s\" id=\"s\" /&gt;\n&lt;input type=\"hidden\" name=\"search-type\" value=\"autor\" /&gt;\n&lt;input id=\"cercabib\" class=\"eb_submit\" name=\"submit\" type=\"submit\" value=\"Cerca\" /&gt;\n&lt;/div&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>And now the code in \"functions.php\":</p>\n\n<pre><code>add_filter('pre_get_posts', 'filtra_inici', 10, 2);\n\nfunction filtra_inici( $query )\n{\n\n global $wp;\n if ( ( is_archive() ) &amp;&amp; $query-&gt;is_main_query() &amp;&amp; !is_admin() ) {\n\nif ( strpos( $wp-&gt;query_vars['category_name'], 'revista-borja' ) !== false ) {\n $query-&gt;set( 'orderby', 'date');\n $query-&gt;set( 'order', 'ASC' );\n}\n\nif (\n $query-&gt;is_search\n &amp;&amp; isset($_GET['search-type'])\n &amp;&amp; $_GET['search-type'] == 'bibliografia'\n) {\n $query-&gt;set( 'post_status', 'publish');\n $query-&gt;set( 'post_type', 'ref_bib');\n}\n\nif (\n $query-&gt;is_search\n &amp;&amp; isset($_GET['search-type'])\n &amp;&amp; 'bibliografia' !== $_GET['search-type']\n) {\n\n $camp = $_GET['search-type'];\n\n if ($camp == 'general') {\n $custom_fields = array('autor', 'publicacio', 'edito', 'observacions');\n }else {\n $custom_fields = array( $camp);\n }\n\n $searchterm = $query-&gt;query_vars['s'];\n // we have to remove the \"s\" parameter from the query, because it will prevent the posts from being found\n $query-&gt;query_vars['s'] = \"\";\n if ($searchterm != \"\") {\n $meta_query = array('relation' =&gt; 'OR');\n foreach ($custom_fields as $cf) {\n array_push($meta_query, array(\n 'key' =&gt; $cf,\n 'value' =&gt; $searchterm,\n 'compare' =&gt; 'LIKE'\n ));\n }\n $query-&gt;set(\"meta_query\", $meta_query);\n $query-&gt;set( 'post_type', 'ref_bib');\n $query-&gt;set( 'post_status', 'publish');\n };\n}\n}// end is_archive\n}\n</code></pre>\n\n<p>An this filter modifies the where clause to add the search for the post_title in case the user wants to make a general search which includes ALL the custom meta AND the post_title.</p>\n\n<pre><code>add_filter( 'posts_where', 'titol_posts_where', 11, 2 );\nfunction titol_posts_where( $where, &amp;$wp_query )\n{\n global $wpdb;\n global $wp;\n if ($_GET['search-type'] == 'general') {\n $where .= ' OR ' . $wpdb-&gt;posts . '.post_title LIKE \\'' . esc_sql( $wpdb-&gt;esc_like( $_GET['s'] ) ) . '%\\'';\n str_replace(\"LIKE\", \"\", $where);\n }\n return $where;\n }\n</code></pre>\n\n<p>Hope this can be helpful to somebody and thanks again to @tomjnewell , @Joel and @user5200704</p>\n" } ]
2016/04/17
[ "https://wordpress.stackexchange.com/questions/223975", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65514/" ]
I'm making a custom post meta search with the pre\_get\_posts function in my Divi child theme functions.php file. The problem is that the final query gathers not only the results for my custom post field (named 'autor') but other fields like 'post\_title' and 'post\_post' which I have not included. That's the resulting query with the troublesome line highlighted in strong: SELECT SQL\_CALC\_FOUND\_ROWS ebj\_posts.ID FROM ebj\_posts INNER JOIN ebj\_term\_relationships ON (ebj\_posts.ID = ebj\_term\_relationships.object\_id) INNER JOIN ebj\_postmeta ON ( ebj\_posts.ID = ebj\_postmeta.post\_id ) INNER JOIN ebj\_postmeta AS mt1 ON ( ebj\_posts.ID = mt1.post\_id ) WHERE 1=1 AND ( ebj\_term\_relationships.term\_taxonomy\_id IN (456) ) **AND (((ebj\_posts.post\_title LIKE '%Abulafia%') OR (ebj\_posts.post\_content LIKE '%Abulafia%')))** AND ( ebj\_postmeta.meta\_key = 'autor' AND ( ( mt1.meta\_key = 'autor' AND CAST(mt1.meta\_value AS CHAR) LIKE '%Abulafia%' ) ) ) AND ebj\_posts.post\_type IN ('post', 'page', 'attachment', 'project', 'ref\_bib') AND ((ebj\_posts.post\_status = 'publish')) GROUP BY ebj\_posts.ID ORDER BY ebj\_postmeta.meta\_value ASC LIMIT 0, 30" As you can see the word 'Abulafia' is searched in the **post\_title** and **post\_content** fields, which is not intended. This line in bold with the AND arguments come from WP > wp-includes > query line 2196: ``` $search .= $wpdb->prepare( "{$searchand}(($wpdb->posts.post_title $like_op %s) $andor_op ($wpdb->posts.post_content $like_op %s))", $like, $like ); ``` because when I comment these line in the wordpress core code the problem vanish. That's my code in functions.php: ``` function filtra_inici( $query ){ global $wp; if ( ( is_archive() ) && $query->is_main_query() && !is_admin() ) { if ($query->is_search && isset($_GET['search-type']) && $_GET['search-type'] == 'autor') { $query->set( 'post_type', 'ref_bib'); $query->set( 'post_status', 'publish'); $query->set( 'orderby', 'meta_value'); $query->set( 'meta_key', 'autor' ); $query->set( 'order', 'ASC' ); $meta_query = array('relation' => 'AND'); array_push( $meta_query, array( 'key' => 'autor', 'value' => $query->query_vars['s'], 'compare' => 'LIKE' )); $query->set( 'meta_query', $meta_query); } }// end is_archive } ``` Thanks!
Create a another filter to remove post title and post content remove search terms try this if this helpful for you ``` add_filter( 'posts_search', 'custom_post_search_author_do', 10, 2 ); function custom_post_search_author_do($search, $query ){ if( ! empty($search) && $query->is_main_query() && !is_admin() && isset($_GET['search-type']) && $_GET['search-type'] == 'autor' ) $search = ''; return $search; } ```
223,979
<p>I'm trying to display a custom field value added to custom taxonomy on single custom post type. I have articles post type with custom taxonomy called issue. I used the code from <a href="https://github.com/bainternet/Tax-Meta-Class" rel="nofollow">Tax-Meta-Class</a> to add custom field "publication date" to that taxonomy. For each issue I added a "publication date" value. To display the publication date of the child issue on each related single article I tried to use this code:</p> <pre><code>$object_terms = wp_get_object_terms( $post-&gt;ID, 'issue', array( 'fields' =&gt; 'all' ) ); if ( $object_terms ) { foreach ( $object_terms as $term ) { if ( $term-&gt;parent ) { $t_id .= $term-&gt;term_id; $res .= get_tax_meta($t_id,'publication_date'); } } echo $res; } </code></pre> <p>But nothing is displayed. I also tried to use <code>get_term_meta</code> instead of <code>get_tax_meta</code> but got nothing. If I added <code>echo $t_id;</code> It displays the term ID which means that the code can correctly get the term ID but it fails to display the custom field value. Any help please?</p>
[ { "answer_id": 223981, "author": "P-S", "author_id": 38771, "author_profile": "https://wordpress.stackexchange.com/users/38771", "pm_score": 1, "selected": false, "text": "<p>Possible solutions:</p>\n\n<ol>\n<li><p>Check if there's a <strong>prefix</strong> which you setup for the custom field (<a href=\"https://en.bainternet.info/tax-meta-class-faq/#comment-1107\" rel=\"nofollow\">https://en.bainternet.info/tax-meta-class-faq/#comment-1107</a>)</p></li>\n<li><p>Go to the <strong>Tax-meta-class/Tax-meta-class.php</strong> file and find the function you're calling and debug the issue:</p>\n\n<pre><code>// Tax-meta-class.php\n\npublic function get_tax_meta($term_id,$key,$multi = false){\n $t_id = (is_object($term_id))? $term_id-&gt;term_id: $term_id;\n var_dump ($t_id); // debug this\n\n $m = get_option( 'tax_meta_'.$t_id);\n var_dump ($m); // debug this\n\n if (isset($m[$key])){\n return $m[$key];\n }else{\n return '';\n }\n}\n</code></pre></li>\n<li><p>Check the <strong><em>wp_options</em></strong> table and search the <strong><em>option_name</em></strong> column for the option (the parameter of <strong><em>get_option('tax_meta_foo_bar')</em></strong> above). It's either not there or you're missing the prefix for <strong><em>get_option</em></strong> not to return a value.</p></li>\n</ol>\n" }, { "answer_id": 223987, "author": "nisr", "author_id": 73173, "author_profile": "https://wordpress.stackexchange.com/users/73173", "pm_score": 1, "selected": true, "text": "<p>Here what I did &amp; finally problem is solved.\nTo make the code work just use <code>get_term_meta</code> and add <code>true</code> to be like this:</p>\n\n<pre><code> $res .= get_term_meta($t_id,'publication_date',true); \n</code></pre>\n\n<p>I hope this will help any one facing such issue. Also, those who use prefix need to add it before the field name as mentioned by P-S</p>\n" } ]
2016/04/17
[ "https://wordpress.stackexchange.com/questions/223979", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73173/" ]
I'm trying to display a custom field value added to custom taxonomy on single custom post type. I have articles post type with custom taxonomy called issue. I used the code from [Tax-Meta-Class](https://github.com/bainternet/Tax-Meta-Class) to add custom field "publication date" to that taxonomy. For each issue I added a "publication date" value. To display the publication date of the child issue on each related single article I tried to use this code: ``` $object_terms = wp_get_object_terms( $post->ID, 'issue', array( 'fields' => 'all' ) ); if ( $object_terms ) { foreach ( $object_terms as $term ) { if ( $term->parent ) { $t_id .= $term->term_id; $res .= get_tax_meta($t_id,'publication_date'); } } echo $res; } ``` But nothing is displayed. I also tried to use `get_term_meta` instead of `get_tax_meta` but got nothing. If I added `echo $t_id;` It displays the term ID which means that the code can correctly get the term ID but it fails to display the custom field value. Any help please?
Here what I did & finally problem is solved. To make the code work just use `get_term_meta` and add `true` to be like this: ``` $res .= get_term_meta($t_id,'publication_date',true); ``` I hope this will help any one facing such issue. Also, those who use prefix need to add it before the field name as mentioned by P-S
224,009
<p>I have one small problem and I can't find answer...I have created custom post type and custom taxonomy, but my custom taxonomy is showing as sub menu under custom pos type, here is <a href="https://i.stack.imgur.com/DMa9Y.png" rel="nofollow noreferrer"> example what I need</a> how can I do this??? here is how my taxonomy and post type is registered:</p> <pre><code>&lt;?php function inkodus_register_taxonomy() { // set up labels $labels = array( 'name' =&gt; 'Manufactures', 'singular_name' =&gt; 'Manufacture', 'search_items' =&gt; 'Search Manufactures', 'all_items' =&gt; 'All Manufactures', 'edit_item' =&gt; 'Edit Manufacture', 'update_item' =&gt; 'Update Manufacture', 'add_new_item' =&gt; 'Add New Manufactures', 'new_item_name' =&gt; 'New Manufactures', 'menu_name' =&gt; 'Manufactures' ); // register taxonomy register_taxonomy( 'manufactures', 'manufactures', array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'query_var' =&gt; true, 'show_admin_column' =&gt; false, 'show_ui' =&gt; true ) ); } add_action( 'init', __NAMESPACE__ . '\\inkodus_register_taxonomy' ); function inkodus_create_post_type() { //setting up labels $labels = array( 'name' =&gt; 'Furnitures-systems list', 'singular_name' =&gt; 'Furniture-system', 'add_new' =&gt; 'Add New System', 'add_new_item' =&gt; 'Add New Furniture-System', 'edit_item' =&gt; 'Edit System', 'new_item' =&gt; 'New Furniture-system', 'all_items' =&gt; 'All Systems', 'view_item' =&gt; 'View System', 'search_items' =&gt; 'Search furniture-systems', 'not_found' =&gt; 'Furniture systems not found', 'not_found_in_trash' =&gt; 'Furniture systems found in Trash', 'parent_item_colon' =&gt; '', 'menu_name' =&gt; 'Furniture Systems ', ); //registering post type register_post_type( 'furnituresystem', array( 'labels' =&gt; $labels, 'has_archive' =&gt; true, 'public' =&gt; true, 'supports' =&gt; array( 'title', 'editor'), //'excerpt', 'custom-fields', 'thumbnail','page-attributes' ), 'taxonomies' =&gt; array('manufactures' ), 'exclude_from_search' =&gt; false, 'capability_type' =&gt; 'post', 'rewrite' =&gt; array( 'slug' =&gt; 'furnituresystem' ), 'register_meta_box_cb' =&gt; 'add_attributes_metabox' ) ); } add_action( 'init', __NAMESPACE__ . '\\inkodus_create_post_type' ); ?&gt; </code></pre>
[ { "answer_id": 223981, "author": "P-S", "author_id": 38771, "author_profile": "https://wordpress.stackexchange.com/users/38771", "pm_score": 1, "selected": false, "text": "<p>Possible solutions:</p>\n\n<ol>\n<li><p>Check if there's a <strong>prefix</strong> which you setup for the custom field (<a href=\"https://en.bainternet.info/tax-meta-class-faq/#comment-1107\" rel=\"nofollow\">https://en.bainternet.info/tax-meta-class-faq/#comment-1107</a>)</p></li>\n<li><p>Go to the <strong>Tax-meta-class/Tax-meta-class.php</strong> file and find the function you're calling and debug the issue:</p>\n\n<pre><code>// Tax-meta-class.php\n\npublic function get_tax_meta($term_id,$key,$multi = false){\n $t_id = (is_object($term_id))? $term_id-&gt;term_id: $term_id;\n var_dump ($t_id); // debug this\n\n $m = get_option( 'tax_meta_'.$t_id);\n var_dump ($m); // debug this\n\n if (isset($m[$key])){\n return $m[$key];\n }else{\n return '';\n }\n}\n</code></pre></li>\n<li><p>Check the <strong><em>wp_options</em></strong> table and search the <strong><em>option_name</em></strong> column for the option (the parameter of <strong><em>get_option('tax_meta_foo_bar')</em></strong> above). It's either not there or you're missing the prefix for <strong><em>get_option</em></strong> not to return a value.</p></li>\n</ol>\n" }, { "answer_id": 223987, "author": "nisr", "author_id": 73173, "author_profile": "https://wordpress.stackexchange.com/users/73173", "pm_score": 1, "selected": true, "text": "<p>Here what I did &amp; finally problem is solved.\nTo make the code work just use <code>get_term_meta</code> and add <code>true</code> to be like this:</p>\n\n<pre><code> $res .= get_term_meta($t_id,'publication_date',true); \n</code></pre>\n\n<p>I hope this will help any one facing such issue. Also, those who use prefix need to add it before the field name as mentioned by P-S</p>\n" } ]
2016/04/18
[ "https://wordpress.stackexchange.com/questions/224009", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90629/" ]
I have one small problem and I can't find answer...I have created custom post type and custom taxonomy, but my custom taxonomy is showing as sub menu under custom pos type, here is [example what I need](https://i.stack.imgur.com/DMa9Y.png) how can I do this??? here is how my taxonomy and post type is registered: ``` <?php function inkodus_register_taxonomy() { // set up labels $labels = array( 'name' => 'Manufactures', 'singular_name' => 'Manufacture', 'search_items' => 'Search Manufactures', 'all_items' => 'All Manufactures', 'edit_item' => 'Edit Manufacture', 'update_item' => 'Update Manufacture', 'add_new_item' => 'Add New Manufactures', 'new_item_name' => 'New Manufactures', 'menu_name' => 'Manufactures' ); // register taxonomy register_taxonomy( 'manufactures', 'manufactures', array( 'hierarchical' => true, 'labels' => $labels, 'query_var' => true, 'show_admin_column' => false, 'show_ui' => true ) ); } add_action( 'init', __NAMESPACE__ . '\\inkodus_register_taxonomy' ); function inkodus_create_post_type() { //setting up labels $labels = array( 'name' => 'Furnitures-systems list', 'singular_name' => 'Furniture-system', 'add_new' => 'Add New System', 'add_new_item' => 'Add New Furniture-System', 'edit_item' => 'Edit System', 'new_item' => 'New Furniture-system', 'all_items' => 'All Systems', 'view_item' => 'View System', 'search_items' => 'Search furniture-systems', 'not_found' => 'Furniture systems not found', 'not_found_in_trash' => 'Furniture systems found in Trash', 'parent_item_colon' => '', 'menu_name' => 'Furniture Systems ', ); //registering post type register_post_type( 'furnituresystem', array( 'labels' => $labels, 'has_archive' => true, 'public' => true, 'supports' => array( 'title', 'editor'), //'excerpt', 'custom-fields', 'thumbnail','page-attributes' ), 'taxonomies' => array('manufactures' ), 'exclude_from_search' => false, 'capability_type' => 'post', 'rewrite' => array( 'slug' => 'furnituresystem' ), 'register_meta_box_cb' => 'add_attributes_metabox' ) ); } add_action( 'init', __NAMESPACE__ . '\\inkodus_create_post_type' ); ?> ```
Here what I did & finally problem is solved. To make the code work just use `get_term_meta` and add `true` to be like this: ``` $res .= get_term_meta($t_id,'publication_date',true); ``` I hope this will help any one facing such issue. Also, those who use prefix need to add it before the field name as mentioned by P-S
224,023
<p>I want to allow my client to change some introductory text on a custom post archive page (eg. <code>archive-unicorn.php</code>), but I can't see how to do this.</p> <p>I guess one way I could do this is would be to create a page template page instead (eg. <code>page-unicorn.php</code>), and use <code>query_posts()</code> to get when I want on the page instead.</p> <p>What's the best way to do this?</p>
[ { "answer_id": 224028, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 2, "selected": false, "text": "<ol>\n<li><p>You can use <a href=\"https://codex.wordpress.org/Options_API\" rel=\"nofollow\">Options API</a>\nor <a href=\"https://codex.wordpress.org/Settings_API\" rel=\"nofollow\">Setting API</a> to store the data in the database. Write a plugin to create a meta box for the introduction text and show that text on the <code>archive-unicorn.php</code>.</p></li>\n<li><p>Or you can utilize the <code>description</code> parameter when you\n<code>register_post_type</code> and print it in the <code>archive-unicorn.php</code> like this:</p>\n\n<pre><code>$unicorn_obj = get_post_type_object('unicorn');\n\nif ( !empty($unicorn_obj) ) {\n echo $unicorn_obj-&gt;description;\n}\n</code></pre></li>\n<li><p>Or you can <code>add_meta_box</code>, e.g. <code>_is_sticky_unicorn</code>, to the <code>unicorn</code> custom post type then use a query to show the post marked <em>sticky</em> on the very top of the <code>archive-unicorn.php</code>:</p>\n\n<pre><code>if( get_post_meta( $post-&gt;ID, '_is_sticky_unicorn', true ) ) {\n // show your sticky post here\n} else {\n // show the rest here\n}\n</code></pre></li>\n</ol>\n" }, { "answer_id": 224042, "author": "Narek Zakarian", "author_id": 92573, "author_profile": "https://wordpress.stackexchange.com/users/92573", "pm_score": 2, "selected": false, "text": "<p>You can try to build some options custom page to allow users to change some text. there are many plugins for easily creating that functionality. I will suggest you the most popular - <a href=\"https://www.advancedcustomfields.com/resources/options-page/\" rel=\"nofollow\">ACF - Options Page</a> </p>\n\n<p>You can use the following code with ACF PRO:</p>\n\n<pre><code>/**\n * Create ACF setting page under Campaign CPT menu\n *\n * @since 1.0.0\n */\nif (function_exists('acf_add_options_sub_page')) {\n acf_add_options_sub_page(\n array(\n 'title' =&gt; 'All Campaign Options',\n 'parent' =&gt; 'edit.php?post_type=campaign',\n 'capability' =&gt; 'manage_options'\n )\n );\n}\n</code></pre>\n" }, { "answer_id": 224049, "author": "Amos Lee", "author_id": 73995, "author_profile": "https://wordpress.stackexchange.com/users/73995", "pm_score": 0, "selected": false, "text": "<p>comment is related to post, page, or custom post type content, not an archive page, so I think you rather need add a front form than comment form on archive pages. You can use the \"visual form builder\" or some other front form plugins to get the done.</p>\n" } ]
2016/04/18
[ "https://wordpress.stackexchange.com/questions/224023", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4109/" ]
I want to allow my client to change some introductory text on a custom post archive page (eg. `archive-unicorn.php`), but I can't see how to do this. I guess one way I could do this is would be to create a page template page instead (eg. `page-unicorn.php`), and use `query_posts()` to get when I want on the page instead. What's the best way to do this?
1. You can use [Options API](https://codex.wordpress.org/Options_API) or [Setting API](https://codex.wordpress.org/Settings_API) to store the data in the database. Write a plugin to create a meta box for the introduction text and show that text on the `archive-unicorn.php`. 2. Or you can utilize the `description` parameter when you `register_post_type` and print it in the `archive-unicorn.php` like this: ``` $unicorn_obj = get_post_type_object('unicorn'); if ( !empty($unicorn_obj) ) { echo $unicorn_obj->description; } ``` 3. Or you can `add_meta_box`, e.g. `_is_sticky_unicorn`, to the `unicorn` custom post type then use a query to show the post marked *sticky* on the very top of the `archive-unicorn.php`: ``` if( get_post_meta( $post->ID, '_is_sticky_unicorn', true ) ) { // show your sticky post here } else { // show the rest here } ```
224,029
<p>I'm displaying a list of terms that a post is assigned to by using the following:</p> <pre><code>&lt;?php $terms = get_the_terms( $post-&gt;ID , 'winetype' ); $sep = ', '; foreach ( $terms as $term ) { echo $term-&gt;name; echo $sep; } ?&gt; </code></pre> <p>But we would like the output to be in descending alphabetical order (Z-A), I can't find a way to use order => DESC on this, any suggestions?</p> <p>Many thanks in advanced.</p>
[ { "answer_id": 224031, "author": "Robbert", "author_id": 25834, "author_profile": "https://wordpress.stackexchange.com/users/25834", "pm_score": 4, "selected": true, "text": "<p>You could try this:</p>\n\n<pre><code>// Get posts terms\n$terms = wp_get_post_terms( $post-&gt;ID, 'winetype', array( 'order' =&gt; 'DESC') );\n\n$sep = ', '; \nforeach ( $terms as $term ) { \n echo $term-&gt;name; \n echo $sep; \n} \n</code></pre>\n" }, { "answer_id": 224032, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 2, "selected": false, "text": "<p>Use <code>wp_get_post_terms()</code> instead:</p>\n\n<pre><code>&lt;?php\n$names = wp_get_post_terms(\n $post-&gt;ID,\n 'winetype',\n array(\n 'orderby' =&gt; 'name',\n 'order' =&gt; 'DESC',\n 'fields' =&gt; 'names'\n );\n\necho implode(', ', $names); // to avoid trailing separator\n</code></pre>\n\n<p><strong>Updated</strong> by virtue of to @Pieter Goosen comment.</p>\n\n<pre><code>$terms = get_the_terms( $post-&gt;ID , 'winetype' ); \n\nif($terms) { // check the variable is not empty\n\n // compare terms\n function cmp($a, $b)\n {\n return strcmp($b-&gt;name, $a-&gt;name); // in reverse order to get DESC\n }\n\n // sort terms using comparison function\n usort($terms, 'cmp');\n\n // get names from objects\n function my_function($z)\n {\n return $z-&gt;name;\n }\n\n // map names array using my_function()\n $term_names = array_map('my_function', $terms);\n\n // define separator\n $separator = ', ';\n\n // get string by imploding the array using the separator \n $term_names = implode($separator, $term_names);\n\n echo $term_names; // OR return\n\n}\n</code></pre>\n" } ]
2016/04/18
[ "https://wordpress.stackexchange.com/questions/224029", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34820/" ]
I'm displaying a list of terms that a post is assigned to by using the following: ``` <?php $terms = get_the_terms( $post->ID , 'winetype' ); $sep = ', '; foreach ( $terms as $term ) { echo $term->name; echo $sep; } ?> ``` But we would like the output to be in descending alphabetical order (Z-A), I can't find a way to use order => DESC on this, any suggestions? Many thanks in advanced.
You could try this: ``` // Get posts terms $terms = wp_get_post_terms( $post->ID, 'winetype', array( 'order' => 'DESC') ); $sep = ', '; foreach ( $terms as $term ) { echo $term->name; echo $sep; } ```
224,035
<p>Checking my error log on the server I continually see the error:</p> <pre><code>PHP Warning: Division by zero in /public_html/wp-content/themes/sass-wordpress-bootstrap-master/image.php on line 95 </code></pre> <p>Here is the code where that error is occurring:</p> <pre><code>$imgmeta = wp_get_attachment_metadata( $id ); // Convert the shutter speed retrieve from database to fraction if ((1 / $imgmeta['image_meta']['shutter_speed']) &gt; 1) { if ((number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1)) == 1.3 or number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1) == 1.5 or number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1) == 1.6 or number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1) == 2.5){ $pshutter = "1/" . number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1, '.', '') . " second"; } else{ $pshutter = "1/" . number_format((1 / $imgmeta['image_meta']['shutter_speed']), 0, '.', '') . " second"; } } else{ $pshutter = $imgmeta['image_meta']['shutter_speed'] . " seconds"; } </code></pre> <p>I'm not ever sure really when this would be called. Could a bot be triggering this error?</p>
[ { "answer_id": 224038, "author": "Bruno Cantuaria", "author_id": 65717, "author_profile": "https://wordpress.stackexchange.com/users/65717", "pm_score": 0, "selected": false, "text": "<p>Even that you're sure that all your images have the 'shutter_speed' declared and more than 0 (although your error report is saying that some does not have), it's a good practice to validate it.</p>\n\n<p>Try including a new parent if like this:</p>\n\n<pre><code>if ( isset($imgmeta['image_meta']['shutter_speed']) &amp;&amp; (intval($imgmeta['image_meta']['shutter_speed'])&gt;0) ) {\n ...\n} else {\n $pshutter = 'unknow';\n}\n</code></pre>\n" }, { "answer_id": 224043, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 3, "selected": true, "text": "<p>shutter speed is one of the exif data wordpress tries to extract from images when uploaded. If the image do not contain the info it will be zero, hence your division by zero error. Somewhere before that code you should check if the image even needs to go there. If it is not a photo then probably not.</p>\n" }, { "answer_id": 224053, "author": "brandozz", "author_id": 64789, "author_profile": "https://wordpress.stackexchange.com/users/64789", "pm_score": 0, "selected": false, "text": "<p>The error is being generated on image attachment pages, so this is most likely a bot. But I added a check before the shutter speed is converted to a fraction: </p>\n\n<pre><code>$imgmeta = wp_get_attachment_metadata( $id );\n $imgShutter = $imgmeta['image_meta']['shutter_speed'];\n // Convert the shutter speed retrieve from database to fraction\n\n if ($imgShutter &gt; 0) {\n\n if ((1 / $imgmeta['image_meta']['shutter_speed']) &gt; 1)\n {\n if ((number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1)) == 1.3\n or number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1) == 1.5\n or number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1) == 1.6\n or number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1) == 2.5){\n $pshutter = \"1/\" . number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1, '.', '') . \" second\";\n }\n else{\n $pshutter = \"1/\" . number_format((1 / $imgmeta['image_meta']['shutter_speed']), 0, '.', '') . \" second\";\n }\n }\n else{\n $pshutter = $imgmeta['image_meta']['shutter_speed'] . \" seconds\";\n }\n }\n</code></pre>\n" } ]
2016/04/18
[ "https://wordpress.stackexchange.com/questions/224035", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64789/" ]
Checking my error log on the server I continually see the error: ``` PHP Warning: Division by zero in /public_html/wp-content/themes/sass-wordpress-bootstrap-master/image.php on line 95 ``` Here is the code where that error is occurring: ``` $imgmeta = wp_get_attachment_metadata( $id ); // Convert the shutter speed retrieve from database to fraction if ((1 / $imgmeta['image_meta']['shutter_speed']) > 1) { if ((number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1)) == 1.3 or number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1) == 1.5 or number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1) == 1.6 or number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1) == 2.5){ $pshutter = "1/" . number_format((1 / $imgmeta['image_meta']['shutter_speed']), 1, '.', '') . " second"; } else{ $pshutter = "1/" . number_format((1 / $imgmeta['image_meta']['shutter_speed']), 0, '.', '') . " second"; } } else{ $pshutter = $imgmeta['image_meta']['shutter_speed'] . " seconds"; } ``` I'm not ever sure really when this would be called. Could a bot be triggering this error?
shutter speed is one of the exif data wordpress tries to extract from images when uploaded. If the image do not contain the info it will be zero, hence your division by zero error. Somewhere before that code you should check if the image even needs to go there. If it is not a photo then probably not.
224,068
<p>I have this...</p> <pre><code>&lt;?php echo strip_tags (get_the_term_list( $post-&gt;ID, 'school-year-level', ' ',', ')); ?&gt; </code></pre> <p>which nicely unlinks and comma separates a list of terms from a specified custom taxonomy (school-year-level). However the list isn't in the order I want. I've hunted down this... <a href="http://codex.wordpress.org/Function_Reference/wp_get_object_terms" rel="nofollow">http://codex.wordpress.org/Function_Reference/wp_get_object_terms</a></p> <pre><code>&lt;?php $product_terms = wp_get_object_terms( $post-&gt;ID, 'school-year-level', $args ); $args = array('orderby' =&gt; 'slug', 'order' =&gt; 'ASC', 'fields' =&gt; 'all'); if ( ! empty( $product_terms ) ) { if ( ! is_wp_error( $product_terms ) ) { foreach( $product_terms as $term ) { echo '&lt;a href="' . get_term_link( $term-&gt;slug, 'school-year-level' ) . '"&gt;' . esc_html( $term-&gt;name ) . '&lt;/a&gt; '; } } } ?&gt; </code></pre> <p>but my attempts to 1. make it a comma separated list, and 2. get the <code>orderby</code> $args to work 3. <code>strip_tags</code> it haven't been working for me :(</p>
[ { "answer_id": 224074, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 1, "selected": false, "text": "<p>Try this (tested on my dev site):</p>\n\n<pre><code>$taxonomy = 'name-of-your-taxonomy';\n$args = array('orderby' =&gt; 'slug', 'order' =&gt; 'ASC', 'fields' =&gt; 'all');\n$product_terms = wp_get_object_terms( $post-&gt;ID, $taxonomy, $args );\n\nif ( ! empty( $product_terms ) &amp;&amp; ! is_wp_error( $product_terms ) ) {\n $terms = array();\n foreach( $product_terms as $term ) {\n $terms[] = esc_html( $term-&gt;name );\n }\n echo join( ', ', $terms );\n} \n</code></pre>\n" }, { "answer_id": 224130, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>For the sake of performance, you should rather use <code>get_the_terms()</code> to get the post terms and then use <code>usort</code> to sort the results. <code>wp_get_object_terms()</code> are not cached and therefor requires an extra db call per post queried. </p>\n\n<p>While at it, also, you would want to pass the complete term object to <code>get_term_link()</code>. If the term is not cached, and the slug or ID is passed to <code>get_term_link()</code>, <code>get_term_link()</code> will query the db to get the complete term object, which you already have. Passing the complete term object saves unnecessary db calls or having to look in the term cache for the term object.</p>\n\n<p>Lastly, you should always define <code>$args</code> first before using it. In your original code, you are trying to use <code>$args</code> first, and then define it, this was the main issue for your failure.</p>\n\n<p>Anyways, you can use the following idea to sort your post terms</p>\n\n<pre><code>$product_terms = get_the_terms( get_the_ID(), 'school-year-level' );\n\n// Make sure we have terms and also check for WP_Error object\nif ( $product_terms\n &amp;&amp; !is_wp_error( $product_terms )\n) {\n @usort( $product_terms, function ( $a, $b )\n {\n return strcasecmp( \n $a-&gt;slug,\n $b-&gt;slug\n );\n });\n\n // Display your terms as normal\n $term_list = [];\n foreach ( $product_terms as $term ) \n $term_list[] = esc_html( $term-&gt;name );\n\n echo implode( ', ', $term_list );\n}\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>To make clicable links that link back to the term's archive page, you need to replace </p>\n\n<pre><code>$term_list[] = esc_html( $term-&gt;name );\n</code></pre>\n\n<p>with </p>\n\n<pre><code>$term_list[] = '&lt;a href=\"' . get_term_link( $term ) . '\"&gt;' . esc_html( $term-&gt;name ) . '&lt;/a&gt;';\n</code></pre>\n\n<p>Note, if you pass the complete term object to <code>get_term_link()</code>, you do not need to pass the taxonomy. The taxonomy is gathered from the term object. </p>\n" } ]
2016/04/18
[ "https://wordpress.stackexchange.com/questions/224068", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37346/" ]
I have this... ``` <?php echo strip_tags (get_the_term_list( $post->ID, 'school-year-level', ' ',', ')); ?> ``` which nicely unlinks and comma separates a list of terms from a specified custom taxonomy (school-year-level). However the list isn't in the order I want. I've hunted down this... <http://codex.wordpress.org/Function_Reference/wp_get_object_terms> ``` <?php $product_terms = wp_get_object_terms( $post->ID, 'school-year-level', $args ); $args = array('orderby' => 'slug', 'order' => 'ASC', 'fields' => 'all'); if ( ! empty( $product_terms ) ) { if ( ! is_wp_error( $product_terms ) ) { foreach( $product_terms as $term ) { echo '<a href="' . get_term_link( $term->slug, 'school-year-level' ) . '">' . esc_html( $term->name ) . '</a> '; } } } ?> ``` but my attempts to 1. make it a comma separated list, and 2. get the `orderby` $args to work 3. `strip_tags` it haven't been working for me :(
For the sake of performance, you should rather use `get_the_terms()` to get the post terms and then use `usort` to sort the results. `wp_get_object_terms()` are not cached and therefor requires an extra db call per post queried. While at it, also, you would want to pass the complete term object to `get_term_link()`. If the term is not cached, and the slug or ID is passed to `get_term_link()`, `get_term_link()` will query the db to get the complete term object, which you already have. Passing the complete term object saves unnecessary db calls or having to look in the term cache for the term object. Lastly, you should always define `$args` first before using it. In your original code, you are trying to use `$args` first, and then define it, this was the main issue for your failure. Anyways, you can use the following idea to sort your post terms ``` $product_terms = get_the_terms( get_the_ID(), 'school-year-level' ); // Make sure we have terms and also check for WP_Error object if ( $product_terms && !is_wp_error( $product_terms ) ) { @usort( $product_terms, function ( $a, $b ) { return strcasecmp( $a->slug, $b->slug ); }); // Display your terms as normal $term_list = []; foreach ( $product_terms as $term ) $term_list[] = esc_html( $term->name ); echo implode( ', ', $term_list ); } ``` EDIT ---- To make clicable links that link back to the term's archive page, you need to replace ``` $term_list[] = esc_html( $term->name ); ``` with ``` $term_list[] = '<a href="' . get_term_link( $term ) . '">' . esc_html( $term->name ) . '</a>'; ``` Note, if you pass the complete term object to `get_term_link()`, you do not need to pass the taxonomy. The taxonomy is gathered from the term object.
224,087
<p><strong>I'm currently getting this error in the front-end only (not inside /wp-admin):</strong></p> <pre><code>Warning: mysqli_real_connect(): (HY000/1203): User xxx already has more than 'max_user_connections' active connections in /hermes/.../public_html/myhome/wp-includes/wp-db.php on line 1489 Warning: mysql_connect(): User xxx already has more than 'max_user_connections' active connections in /hermes/.../public_html/myhome/wp-includes/wp-db.php on line 1515 Error establishing a database connection </code></pre> <p>And I'm wondering how come this appear when I'm the only visitor? I'm using WP 4.5.</p> <p><strong>I did contact the host who was kind enough to reply as below:</strong></p> <pre><code>Currently your website is showing 'Error establishing a database connection' because the user of the database has exceeded the concurrent connection limit for a user of a database, which is 10. This is the reason website is loads database error. The script throws the concurrent connection error when number of database connections exceed the limit set on the server. In our shared platform, we allow maximum of 10 concurrent connections to a database, which is ideal in the shared platform and it is not possible to increase this limit. The query limit for your website will be reset within couple of hours so you should be able to access the database after couple of hours. There are two cases the script loads above error, one is when there is a high traffic to the website and database concurrent connection hits the limit and second case is the database connection is not closed in the script, even for the moderate traffic the script loads concurrent connection error. To overcome this issue, you have to close the database connection immediately after fetching the required content from the database. To close the database connection you can use mysql_close() PHP function with connection parameter. This will help you to use database connection limit efficiently. </code></pre> <p>In other words, everything is fine at our end, it's a WP error.</p>
[ { "answer_id": 224074, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 1, "selected": false, "text": "<p>Try this (tested on my dev site):</p>\n\n<pre><code>$taxonomy = 'name-of-your-taxonomy';\n$args = array('orderby' =&gt; 'slug', 'order' =&gt; 'ASC', 'fields' =&gt; 'all');\n$product_terms = wp_get_object_terms( $post-&gt;ID, $taxonomy, $args );\n\nif ( ! empty( $product_terms ) &amp;&amp; ! is_wp_error( $product_terms ) ) {\n $terms = array();\n foreach( $product_terms as $term ) {\n $terms[] = esc_html( $term-&gt;name );\n }\n echo join( ', ', $terms );\n} \n</code></pre>\n" }, { "answer_id": 224130, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>For the sake of performance, you should rather use <code>get_the_terms()</code> to get the post terms and then use <code>usort</code> to sort the results. <code>wp_get_object_terms()</code> are not cached and therefor requires an extra db call per post queried. </p>\n\n<p>While at it, also, you would want to pass the complete term object to <code>get_term_link()</code>. If the term is not cached, and the slug or ID is passed to <code>get_term_link()</code>, <code>get_term_link()</code> will query the db to get the complete term object, which you already have. Passing the complete term object saves unnecessary db calls or having to look in the term cache for the term object.</p>\n\n<p>Lastly, you should always define <code>$args</code> first before using it. In your original code, you are trying to use <code>$args</code> first, and then define it, this was the main issue for your failure.</p>\n\n<p>Anyways, you can use the following idea to sort your post terms</p>\n\n<pre><code>$product_terms = get_the_terms( get_the_ID(), 'school-year-level' );\n\n// Make sure we have terms and also check for WP_Error object\nif ( $product_terms\n &amp;&amp; !is_wp_error( $product_terms )\n) {\n @usort( $product_terms, function ( $a, $b )\n {\n return strcasecmp( \n $a-&gt;slug,\n $b-&gt;slug\n );\n });\n\n // Display your terms as normal\n $term_list = [];\n foreach ( $product_terms as $term ) \n $term_list[] = esc_html( $term-&gt;name );\n\n echo implode( ', ', $term_list );\n}\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>To make clicable links that link back to the term's archive page, you need to replace </p>\n\n<pre><code>$term_list[] = esc_html( $term-&gt;name );\n</code></pre>\n\n<p>with </p>\n\n<pre><code>$term_list[] = '&lt;a href=\"' . get_term_link( $term ) . '\"&gt;' . esc_html( $term-&gt;name ) . '&lt;/a&gt;';\n</code></pre>\n\n<p>Note, if you pass the complete term object to <code>get_term_link()</code>, you do not need to pass the taxonomy. The taxonomy is gathered from the term object. </p>\n" } ]
2016/04/18
[ "https://wordpress.stackexchange.com/questions/224087", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89346/" ]
**I'm currently getting this error in the front-end only (not inside /wp-admin):** ``` Warning: mysqli_real_connect(): (HY000/1203): User xxx already has more than 'max_user_connections' active connections in /hermes/.../public_html/myhome/wp-includes/wp-db.php on line 1489 Warning: mysql_connect(): User xxx already has more than 'max_user_connections' active connections in /hermes/.../public_html/myhome/wp-includes/wp-db.php on line 1515 Error establishing a database connection ``` And I'm wondering how come this appear when I'm the only visitor? I'm using WP 4.5. **I did contact the host who was kind enough to reply as below:** ``` Currently your website is showing 'Error establishing a database connection' because the user of the database has exceeded the concurrent connection limit for a user of a database, which is 10. This is the reason website is loads database error. The script throws the concurrent connection error when number of database connections exceed the limit set on the server. In our shared platform, we allow maximum of 10 concurrent connections to a database, which is ideal in the shared platform and it is not possible to increase this limit. The query limit for your website will be reset within couple of hours so you should be able to access the database after couple of hours. There are two cases the script loads above error, one is when there is a high traffic to the website and database concurrent connection hits the limit and second case is the database connection is not closed in the script, even for the moderate traffic the script loads concurrent connection error. To overcome this issue, you have to close the database connection immediately after fetching the required content from the database. To close the database connection you can use mysql_close() PHP function with connection parameter. This will help you to use database connection limit efficiently. ``` In other words, everything is fine at our end, it's a WP error.
For the sake of performance, you should rather use `get_the_terms()` to get the post terms and then use `usort` to sort the results. `wp_get_object_terms()` are not cached and therefor requires an extra db call per post queried. While at it, also, you would want to pass the complete term object to `get_term_link()`. If the term is not cached, and the slug or ID is passed to `get_term_link()`, `get_term_link()` will query the db to get the complete term object, which you already have. Passing the complete term object saves unnecessary db calls or having to look in the term cache for the term object. Lastly, you should always define `$args` first before using it. In your original code, you are trying to use `$args` first, and then define it, this was the main issue for your failure. Anyways, you can use the following idea to sort your post terms ``` $product_terms = get_the_terms( get_the_ID(), 'school-year-level' ); // Make sure we have terms and also check for WP_Error object if ( $product_terms && !is_wp_error( $product_terms ) ) { @usort( $product_terms, function ( $a, $b ) { return strcasecmp( $a->slug, $b->slug ); }); // Display your terms as normal $term_list = []; foreach ( $product_terms as $term ) $term_list[] = esc_html( $term->name ); echo implode( ', ', $term_list ); } ``` EDIT ---- To make clicable links that link back to the term's archive page, you need to replace ``` $term_list[] = esc_html( $term->name ); ``` with ``` $term_list[] = '<a href="' . get_term_link( $term ) . '">' . esc_html( $term->name ) . '</a>'; ``` Note, if you pass the complete term object to `get_term_link()`, you do not need to pass the taxonomy. The taxonomy is gathered from the term object.
224,091
<p>I have be trying this all day but it is not working how do I set a role for the current user I am inserting with the <code>wp_insert_user()</code> function</p> <pre><code>$userdata = array( 'user_login' =&gt; $username, 'user_email' =&gt; $email, 'user_pass' =&gt; $password, 'user_url' =&gt; $website, 'first_name' =&gt; $first_name, 'last_name' =&gt; $last_name, 'nickname' =&gt; $nickname, 'description' =&gt; $bio, 'role' =&gt; 'Editor' ); $user = wp_insert_user( $userdata ); </code></pre>
[ { "answer_id": 224093, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 4, "selected": true, "text": "<pre><code>$WP_array = array (\n 'user_login' =&gt; $username,\n 'user_email' =&gt; $email,\n 'user_pass' =&gt; $password,\n 'user_url' =&gt; $website,\n 'first_name' =&gt; $first_name,\n 'last_name' =&gt; $last_name,\n 'nickname' =&gt; $nickname,\n 'description' =&gt; $bio,\n ) ;\n\n $id = wp_insert_user( $WP_array ) ;\n\n wp_update_user( array ('ID' =&gt; $id, 'role' =&gt; 'editor') ) ;\n</code></pre>\n\n<p>Since you are looking for working solutions, this one should work, and it is only the helpful answer candidate. I am ware that this may not be the best solution, maybe not even close, but it should work.</p>\n" }, { "answer_id": 226362, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 3, "selected": false, "text": "<p>After digging deeper, and checking on my end, I found this script will work just fine.</p>\n\n<pre><code>$userdata = array(\n'user_login' =&gt; $username,\n'user_email' =&gt; $email,\n'user_pass' =&gt; $password,\n'user_url' =&gt; $website,\n'first_name' =&gt; $first_name,\n'last_name' =&gt; $last_name,\n'nickname' =&gt; $nickname,\n'description' =&gt; $bio,\n'role' =&gt; 'editor'\n);\n\n$user = wp_insert_user( $userdata );\n</code></pre>\n\n<p>Yet, there isn't anything mysterious in this script. Looks like the roles need to use lowercase, and you need to blame this function, that I found after days of analysis. </p>\n\n<pre><code>/wp-includes/class-wp-roles.php\n284: /**\n285: * Whether role name is currently in the list of available roles.\n286: *\n287: * @since 2.0.0\n288: * @access public\n289: *\n290: * @param string $role Role name to look up.\n291: * @return bool\n292: */\n293: public function is_role( $role ) {\n</code></pre>\n\n<p>You can check for your self if you write code like this in <code>functions.php</code>.</p>\n\n<pre><code>$r = new WP_Roles();\nvar_dump(\"editor\", $r-&gt;is_role(\"editor\"));\nvar_dump(\"Editor\", $r-&gt;is_role(\"Editor\"));\ndie();\n</code></pre>\n\n<p>You will get the end result like this.</p>\n\n<pre><code>string(6) \"editor\" bool(true) string(6) \"Editor\" bool(false) \n</code></pre>\n\n<p>This means the <code>editor</code> for the role name is OK and the <code>Editor</code> is not OK.</p>\n\n<p>We must make a note that if you set an empty role like this <code>'role' =&gt; \"\"</code> this will result in setting no roles at all (like @TheBeast experienced at the first place with <code>Editor</code> name where at the end no role has been set).</p>\n\n<p>On the other hand if you would omit <code>'role'</code> key then your user will take the default role. The default role is usually the <code>editor</code>, but it is up to you to customize since that info you can get via <code>get_option('default_role')</code>, end set via <code>set_option</code> function.</p>\n\n<p>In the past I found indications that the code from @TheBeast would actually work. (<a href=\"https://wordpress.org/support/topic/wp_insert_user-function-user-roles?replies=3\" rel=\"noreferrer\">https://wordpress.org/support/topic/wp_insert_user-function-user-roles?replies=3</a>) </p>\n\n<p>What is actually important for us is a process of adding roles. You can write like:</p>\n\n<pre><code>add_action( 'init', 'plugin_add_role');\nfunction plugin_add_role( 'reviewer', 'Reviewer', $caps );\n</code></pre>\n\n<p>In here your <code>$caps</code> capabilities are something like:</p>\n\n<pre><code>$caps = array(\n 'read' =&gt; true,\n 'edit_posts' =&gt; true,\n 'edit_others_posts' =&gt; true,\n 'edit_private_posts' =&gt; true,\n 'edit_published_posts' =&gt; true,\n 'read_private_posts' =&gt; true,\n 'edit_pages' =&gt; true,\n 'edit_others_pages' =&gt; true,\n 'edit_private_pages' =&gt; true,\n 'edit_published_pages' =&gt; true,\n 'read_private_pages' =&gt; true,\n );\n</code></pre>\n\n<p>You can read more about capabilities in the codex <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"noreferrer\">https://codex.wordpress.org/Roles_and_Capabilities</a>.</p>\n" }, { "answer_id": 394004, "author": "user2215032", "author_id": 210903, "author_profile": "https://wordpress.stackexchange.com/users/210903", "pm_score": 0, "selected": false, "text": "<p>just user lower case &amp; in two words roles using underline instead of space</p>\n<pre><code>'role' =&gt; 'Editor' -------&gt; 'role' =&gt; 'editor'\n\n'role' =&gt; 'Shop manager' -------&gt; 'role' =&gt; 'shop_manager'\n</code></pre>\n" } ]
2016/04/18
[ "https://wordpress.stackexchange.com/questions/224091", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86976/" ]
I have be trying this all day but it is not working how do I set a role for the current user I am inserting with the `wp_insert_user()` function ``` $userdata = array( 'user_login' => $username, 'user_email' => $email, 'user_pass' => $password, 'user_url' => $website, 'first_name' => $first_name, 'last_name' => $last_name, 'nickname' => $nickname, 'description' => $bio, 'role' => 'Editor' ); $user = wp_insert_user( $userdata ); ```
``` $WP_array = array ( 'user_login' => $username, 'user_email' => $email, 'user_pass' => $password, 'user_url' => $website, 'first_name' => $first_name, 'last_name' => $last_name, 'nickname' => $nickname, 'description' => $bio, ) ; $id = wp_insert_user( $WP_array ) ; wp_update_user( array ('ID' => $id, 'role' => 'editor') ) ; ``` Since you are looking for working solutions, this one should work, and it is only the helpful answer candidate. I am ware that this may not be the best solution, maybe not even close, but it should work.
224,118
<p>I'm new from wordpress and i want improve security of wordpress multisite by hiding non public resources, eg. wp-admin, wp-config etc.</p> <p>My setting seem to work, but i don't know if this setting can break something (core features, popular plug-in, etc.)</p> <ol> <li>Are my settings good in general way?</li> <li>My settings improve real security or i'm wasting my time?</li> </ol> <p>httpd-vhosts.conf (apache)</p> <pre><code># Disallow public access php for .htaccess and .htpasswd files &lt;Files ".ht*"&gt; Require all denied &lt;/Files&gt; # Disallow public access for *.php files in upload directory &lt;Directory "/htdocs/wp-content/uploads/"&gt; &lt;Files "*.php"&gt; deny from all &lt;/Files&gt; &lt;/Directory&gt; # Disallow public access for... &lt;Files "wp-config.php"&gt; order allow,deny deny from all &lt;/Files&gt; &lt;Files "readme.html"&gt; order allow,deny deny from all &lt;/Files&gt; &lt;Files "license.html"&gt; order allow,deny deny from all &lt;/Files&gt; &lt;Files "license.txt"&gt; order allow,deny deny from all &lt;/Files&gt; # Because we do not use any remote connections to publish on WP &lt;Files "xmlrpc.php"&gt; order allow,deny deny from all &lt;/Files&gt; </code></pre> <p>.htaccess</p> <pre><code>RewriteEngine On RewriteBase / # List of ACME company IP Address SetEnvIf Remote_Addr "^127\.0\.0\." NETWORK=ACME SetEnvIf Remote_Addr "^XX\.XX\.XX\.XX$" NETWORK=ACME SetEnvIf Remote_Addr "^XX\.XX\.XX\.XX$" NETWORK=ACME SetEnvIf Remote_Addr "^XX\.XX\.XX\.XX$" NETWORK=ACME # Disallow access to wp-admin and wp-login.php RewriteCond %{SCRIPT_FILENAME} !^(.*)admin-ajax\.php$ # allow fo admin-ajax.php RewriteCond %{ENV:NETWORK} !^ACME$ # allow for ACME RewriteCond %{SCRIPT_FILENAME} ^(.*)?wp-login\.php$ [OR] RewriteCond %{REQUEST_URI} ^(.*)?wp-admin\/ RewriteRule ^(.*)$ - [R=403,L] # Block user enumeration RewriteCond %{REQUEST_URI} ^/$ RewriteCond %{QUERY_STRING} ^/?author=([0-9]*) RewriteRule ^(.*)$ / [L,R=301] # Block the include-only files. # see: http://codex.wordpress.org/Hardening_WordPress (Securing wp-includes) RewriteRule ^wp-admin/includes/ - [F,L] RewriteRule !^wp-includes/ - [S=3] #RewriteRule ^wp-includes/[^/]+\.php$ - [F,L] # Comment for Multisite RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L] RewriteRule ^wp-includes/theme-compat/ - [F,L] </code></pre> <p>function.php</p> <pre><code>&lt;?php // Remove unnecessary meta tags // &lt;meta name="generator" content="WordPress 4.1" /&gt; remove_action('wp_head', 'wp_generator'); // Disable WordPress Login Hints function no_wordpress_errors(){ return 'GET OFF MY LAWN !! RIGHT NOW !!'; } add_filter( 'login_errors', 'no_wordpress_errors' ); </code></pre> <p>wp-config.php</p> <pre><code>&lt;?php define('DISALLOW_FILE_EDIT', true); define('DISALLOW_FILE_MODS', true); </code></pre>
[ { "answer_id": 227744, "author": "Uncle Iroh", "author_id": 44927, "author_profile": "https://wordpress.stackexchange.com/users/44927", "pm_score": -1, "selected": false, "text": "<p>Are you running your site on cPanel?</p>\n\n<p>If so, explore your control panel and you'll see a few great modules. </p>\n\n<ul>\n<li>hotlink protection</li>\n<li>leech protection</li>\n</ul>\n\n<p>Under <strong>Advanced</strong> tab, look for <strong>indexes.</strong> Once you click you can customize and \"hide non public\" resources very easily.</p>\n\n<p><a href=\"https://i.stack.imgur.com/hBnl8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hBnl8.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 228762, "author": "sunilsingh", "author_id": 89975, "author_profile": "https://wordpress.stackexchange.com/users/89975", "pm_score": 1, "selected": false, "text": "<p>Using <code>remove_action()</code> can be remove unnecessary links for example:</p>\n\n<pre><code>remove_action('wp_head', 'rsd_link'); //removes EditURI/RSD (Really Simple Discovery) link.\nremove_action('wp_head', 'wlwmanifest_link'); //removes wlwmanifest (Windows Live Writer) link.\nremove_action('wp_head', 'wp_generator'); //removes meta name generator.\nremove_action('wp_head', 'wp_shortlink_wp_head'); //removes shortlink.\nremove_action( 'wp_head', 'feed_links', 2 ); //removes feed links.\nremove_action('wp_head', 'feed_links_extra', 3 ); //removes comments feed. \n</code></pre>\n" } ]
2016/04/19
[ "https://wordpress.stackexchange.com/questions/224118", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92207/" ]
I'm new from wordpress and i want improve security of wordpress multisite by hiding non public resources, eg. wp-admin, wp-config etc. My setting seem to work, but i don't know if this setting can break something (core features, popular plug-in, etc.) 1. Are my settings good in general way? 2. My settings improve real security or i'm wasting my time? httpd-vhosts.conf (apache) ``` # Disallow public access php for .htaccess and .htpasswd files <Files ".ht*"> Require all denied </Files> # Disallow public access for *.php files in upload directory <Directory "/htdocs/wp-content/uploads/"> <Files "*.php"> deny from all </Files> </Directory> # Disallow public access for... <Files "wp-config.php"> order allow,deny deny from all </Files> <Files "readme.html"> order allow,deny deny from all </Files> <Files "license.html"> order allow,deny deny from all </Files> <Files "license.txt"> order allow,deny deny from all </Files> # Because we do not use any remote connections to publish on WP <Files "xmlrpc.php"> order allow,deny deny from all </Files> ``` .htaccess ``` RewriteEngine On RewriteBase / # List of ACME company IP Address SetEnvIf Remote_Addr "^127\.0\.0\." NETWORK=ACME SetEnvIf Remote_Addr "^XX\.XX\.XX\.XX$" NETWORK=ACME SetEnvIf Remote_Addr "^XX\.XX\.XX\.XX$" NETWORK=ACME SetEnvIf Remote_Addr "^XX\.XX\.XX\.XX$" NETWORK=ACME # Disallow access to wp-admin and wp-login.php RewriteCond %{SCRIPT_FILENAME} !^(.*)admin-ajax\.php$ # allow fo admin-ajax.php RewriteCond %{ENV:NETWORK} !^ACME$ # allow for ACME RewriteCond %{SCRIPT_FILENAME} ^(.*)?wp-login\.php$ [OR] RewriteCond %{REQUEST_URI} ^(.*)?wp-admin\/ RewriteRule ^(.*)$ - [R=403,L] # Block user enumeration RewriteCond %{REQUEST_URI} ^/$ RewriteCond %{QUERY_STRING} ^/?author=([0-9]*) RewriteRule ^(.*)$ / [L,R=301] # Block the include-only files. # see: http://codex.wordpress.org/Hardening_WordPress (Securing wp-includes) RewriteRule ^wp-admin/includes/ - [F,L] RewriteRule !^wp-includes/ - [S=3] #RewriteRule ^wp-includes/[^/]+\.php$ - [F,L] # Comment for Multisite RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L] RewriteRule ^wp-includes/theme-compat/ - [F,L] ``` function.php ``` <?php // Remove unnecessary meta tags // <meta name="generator" content="WordPress 4.1" /> remove_action('wp_head', 'wp_generator'); // Disable WordPress Login Hints function no_wordpress_errors(){ return 'GET OFF MY LAWN !! RIGHT NOW !!'; } add_filter( 'login_errors', 'no_wordpress_errors' ); ``` wp-config.php ``` <?php define('DISALLOW_FILE_EDIT', true); define('DISALLOW_FILE_MODS', true); ```
Using `remove_action()` can be remove unnecessary links for example: ``` remove_action('wp_head', 'rsd_link'); //removes EditURI/RSD (Really Simple Discovery) link. remove_action('wp_head', 'wlwmanifest_link'); //removes wlwmanifest (Windows Live Writer) link. remove_action('wp_head', 'wp_generator'); //removes meta name generator. remove_action('wp_head', 'wp_shortlink_wp_head'); //removes shortlink. remove_action( 'wp_head', 'feed_links', 2 ); //removes feed links. remove_action('wp_head', 'feed_links_extra', 3 ); //removes comments feed. ```
224,159
<p>I have been looking for ways to completely remove the All, Published, and Trash webpages for USERS <strong><em>other than the me, the Administrator</em></strong>.</p> <p>So the scenario for me is: I have registered users (which I would like to assign with the roles of authors, contributors, etc). Now, when they log in to my website and access the Posts area, I wish for them not to see these three links (All, Published, Trash). </p> <p>I have tried using the jquery function, which is basically the same as display: none, but I don't think it's the optimal choice. I know there's better ways for me to do this. </p> <p>I did try using plugins, such as Member and Adminimize, among other things, but I can't find the right one. </p> <p>I hope there's someone out there who can help me. Thanks in advance.</p> <p><a href="https://i.stack.imgur.com/xH2mE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xH2mE.png" alt="Remove All, Published, and Trash"></a></p>
[ { "answer_id": 224166, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 2, "selected": false, "text": "<p>Those statuses are turned from <code>get_available_post_statuses()</code>, which in turn gets its values from <code>wp_count_posts()</code>.</p>\n\n<p><code>wp_count_posts()</code> passes it's values through the <code>wp_count_posts</code> filter. So you can tap into that and hijack what gets returned.</p>\n\n<p>Try this:</p>\n\n<pre><code>function _dbdb_wp_count_posts( $counts, $type, $perm ) {\n global $pagenow;\n\n if( 'edit.php' !== $pagenow ){\n return $counts;\n }\n\n if( current_user_can( 'manage_options' ) ){\n return $counts;\n }\n\n $_counts = new stdClass();\n foreach ( $counts as $status =&gt; $count ){\n $_counts-&gt;$status = '';\n }\n\n return $_counts;\n}\nadd_filter('wp_count_posts', '_dbdb_wp_count_posts', 99, 3 );\n</code></pre>\n\n<p>What this does is check if we're on the <code>edit.php</code> page in the Admin,and if not, just return the counts.</p>\n\n<p>Then it checks if the current user can manage site options, which only an Administrator can. If the current user can, all counts are returned.</p>\n\n<p>If you get past this check, it assumes you're not an Administrator, so it resets all counts to <code>0</code>, effectively removing the status links.</p>\n\n<p><strong>Note:</strong> the \"all\" and \"mine\" status links are hard-coded in the <code>get_views()</code> method of the <code>WP_Posts_List_Table</code> Class and aren't filterable.</p>\n\n<p>I quickly tested this on my dev server, first signing in as an Admin, and then as an Author. It worked as expected, but be sure to test thoroughly.</p>\n" }, { "answer_id": 224253, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>The <code>WP_Posts_List_Table</code> class extends <code>WP_List_Table</code> and within the <code>WP_List_Table::views()</code> method we have the following dynamic <em>views</em> filter:</p>\n\n<pre><code>/**\n * Filter the list of available list table views.\n *\n * The dynamic portion of the hook name, `$this-&gt;screen-&gt;id`, refers\n * to the ID of the current screen, usually a string.\n *\n * @since 3.5.0\n *\n * @param array $views An array of available list table views.\n */\n $views = apply_filters( \"views_{$this-&gt;screen-&gt;id}\", $views );\n</code></pre>\n\n<p>So we can use the generated <code>views_edit-post</code> filter to adjust the views of the <em>post list table</em>. </p>\n\n<h2>Example:</h2>\n\n<p>Let's remove the <em>all</em>, <em>publish</em>, <em>future</em>, <em>sticky</em>, <em>draft</em>, <em>pending</em> and <em>trash</em> for non-admins (<em>PHP 5.4+</em>):</p>\n\n<pre><code>/**\n * Remove the 'all', 'publish', 'future', 'sticky', 'draft', 'pending', 'trash' \n * views for non-admins\n */\nadd_filter( 'views_edit-post', function( $views )\n{\n if( current_user_can( 'manage_options' ) )\n return $views;\n\n $remove_views = [ 'all','publish','future','sticky','draft','pending','trash' ];\n\n foreach( (array) $remove_views as $view )\n {\n if( isset( $views[$view] ) )\n unset( $views[$view] );\n }\n return $views;\n} );\n</code></pre>\n\n<p>where you can modify the <code>$remove_views</code> to your needs. Another approach would be to only pick up <em>mine</em> and only return that view.</p>\n\n<p>Then we could try to force the <em>mine</em> view further with:</p>\n\n<pre><code>/**\n * Force the 'mine' view on the 'edit-post' screen\n */\nadd_action( 'pre_get_posts', function( \\WP_Query $q )\n{\n if( \n is_admin() \n &amp;&amp; $q-&gt;is_main_query() \n &amp;&amp; 'edit-post' === get_current_screen()-&gt;id \n &amp;&amp; ! current_user_can( 'manage_options' )\n )\n $q-&gt;set( 'author', get_current_user_id() ); \n} );\n</code></pre>\n\n<p><strong>Before:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/la8c1.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/la8c1.jpg\" alt=\"before\"></a></p>\n\n<p><strong>After:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/OhwZa.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/OhwZa.jpg\" alt=\"after\"></a></p>\n" }, { "answer_id": 408678, "author": "Ericc Antunes", "author_id": 76267, "author_profile": "https://wordpress.stackexchange.com/users/76267", "pm_score": 0, "selected": false, "text": "<p>Return only &quot;Mine&quot; status</p>\n<pre><code>add_filter( 'views_edit-{your-cpt}', function( $views ) { \n if ( current_user_can( 'manage_options' ) ) {\n return $views;\n }\n return array_filter( $views, fn( $i ) =&gt; 'mine' === $i, ARRAY_FILTER_USE_KEY );\n} );\n</code></pre>\n" } ]
2016/04/19
[ "https://wordpress.stackexchange.com/questions/224159", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92538/" ]
I have been looking for ways to completely remove the All, Published, and Trash webpages for USERS ***other than the me, the Administrator***. So the scenario for me is: I have registered users (which I would like to assign with the roles of authors, contributors, etc). Now, when they log in to my website and access the Posts area, I wish for them not to see these three links (All, Published, Trash). I have tried using the jquery function, which is basically the same as display: none, but I don't think it's the optimal choice. I know there's better ways for me to do this. I did try using plugins, such as Member and Adminimize, among other things, but I can't find the right one. I hope there's someone out there who can help me. Thanks in advance. [![Remove All, Published, and Trash](https://i.stack.imgur.com/xH2mE.png)](https://i.stack.imgur.com/xH2mE.png)
The `WP_Posts_List_Table` class extends `WP_List_Table` and within the `WP_List_Table::views()` method we have the following dynamic *views* filter: ``` /** * Filter the list of available list table views. * * The dynamic portion of the hook name, `$this->screen->id`, refers * to the ID of the current screen, usually a string. * * @since 3.5.0 * * @param array $views An array of available list table views. */ $views = apply_filters( "views_{$this->screen->id}", $views ); ``` So we can use the generated `views_edit-post` filter to adjust the views of the *post list table*. Example: -------- Let's remove the *all*, *publish*, *future*, *sticky*, *draft*, *pending* and *trash* for non-admins (*PHP 5.4+*): ``` /** * Remove the 'all', 'publish', 'future', 'sticky', 'draft', 'pending', 'trash' * views for non-admins */ add_filter( 'views_edit-post', function( $views ) { if( current_user_can( 'manage_options' ) ) return $views; $remove_views = [ 'all','publish','future','sticky','draft','pending','trash' ]; foreach( (array) $remove_views as $view ) { if( isset( $views[$view] ) ) unset( $views[$view] ); } return $views; } ); ``` where you can modify the `$remove_views` to your needs. Another approach would be to only pick up *mine* and only return that view. Then we could try to force the *mine* view further with: ``` /** * Force the 'mine' view on the 'edit-post' screen */ add_action( 'pre_get_posts', function( \WP_Query $q ) { if( is_admin() && $q->is_main_query() && 'edit-post' === get_current_screen()->id && ! current_user_can( 'manage_options' ) ) $q->set( 'author', get_current_user_id() ); } ); ``` **Before:** [![before](https://i.stack.imgur.com/la8c1.jpg)](https://i.stack.imgur.com/la8c1.jpg) **After:** [![after](https://i.stack.imgur.com/OhwZa.jpg)](https://i.stack.imgur.com/OhwZa.jpg)
224,197
<p>How can I add Bootstrap to the Wordpress TwentySixteen Theme without using a plugin? I've tried linking to the stylesheets and scripts within the header/footer, however the theme seems to override something, and I'm unable to get different Bootstrap elements to work on specific pages. For instance, I've tried to get the clickable tabs to work, but no luck.</p> <p>I've tried using the following code: <a href="http://jsfiddle.net/xfw8t/12/" rel="nofollow">http://jsfiddle.net/xfw8t/12/</a></p> <p>While adding the CSS to the header and JS to the footer file:</p> <pre><code>&lt;link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet"&gt; &lt;script src="/scripts/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="/bootstrap/js/bootstrap.min.js"&gt;&lt;/script&gt; </code></pre>
[ { "answer_id": 224235, "author": "Swopnil Dangol", "author_id": 90685, "author_profile": "https://wordpress.stackexchange.com/users/90685", "pm_score": 1, "selected": false, "text": "<p>If you want to link stylesheets and scripts in wordpress,the correct way is to use wp_enqueue_style() and wp_enqueue_scripts() in your functions.php file</p>\n\n<p>Try this in your functions.php file</p>\n\n<pre><code>wp_enqueue_style('bootstrap-css',get_template_directory_uri().'/bootstrap/css/bootstrap.min.css');\nwp_enqueue_script('jquery',get_template_directory_uri().'/scripts/jquery.min.js');\nwp_enqueue_script('bootstrap-js',get_template_directory_uri().'/bootstrap/js/bootstrap.min.js');\n</code></pre>\n" }, { "answer_id": 224323, "author": "Michael Mano", "author_id": 92720, "author_profile": "https://wordpress.stackexchange.com/users/92720", "pm_score": 0, "selected": false, "text": "<p>Swopnil Dangol is correct, However seeing that you are editing a standard wordpress theme in the first place with bootstrap i would not bother</p>\n\n<p>the below answer is the for lazy man.</p>\n\n<pre>\nphp echo get_template_directory_uri(); ?>\n</pre>\n\n<p>infront of the urls</p>\n" } ]
2016/04/19
[ "https://wordpress.stackexchange.com/questions/224197", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92655/" ]
How can I add Bootstrap to the Wordpress TwentySixteen Theme without using a plugin? I've tried linking to the stylesheets and scripts within the header/footer, however the theme seems to override something, and I'm unable to get different Bootstrap elements to work on specific pages. For instance, I've tried to get the clickable tabs to work, but no luck. I've tried using the following code: <http://jsfiddle.net/xfw8t/12/> While adding the CSS to the header and JS to the footer file: ``` <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <script src="/scripts/jquery.min.js"></script> <script src="/bootstrap/js/bootstrap.min.js"></script> ```
If you want to link stylesheets and scripts in wordpress,the correct way is to use wp\_enqueue\_style() and wp\_enqueue\_scripts() in your functions.php file Try this in your functions.php file ``` wp_enqueue_style('bootstrap-css',get_template_directory_uri().'/bootstrap/css/bootstrap.min.css'); wp_enqueue_script('jquery',get_template_directory_uri().'/scripts/jquery.min.js'); wp_enqueue_script('bootstrap-js',get_template_directory_uri().'/bootstrap/js/bootstrap.min.js'); ```
224,219
<p>I'll be brief and hope I can explain my scenario correctly. Here's my scenario. The jQuery slider plugin has an anonymous callback method. I would like to give the Admin the ability to create a function for that callback method. So from the plugin's add/edit pages the admin has a textarea to input the jQuery code. Now the textarea input gets save to the database and when it's passed using the wp_localize_script() it gets pass as a string that does not get recognize as a Javascript/jQuery code. So far, I have only being able to make it work using eval() in order for it to be recognize and to run as a Javascript/jQuery function.</p> <p>On the Admin page:</p> <p><code>&lt;textarea id="callback" name="callback" rows="10" &gt;&lt;?php echo $callback; ?&gt;&lt;/textarea&gt;</code></p> <p>On the wp_localize_script() array:</p> <pre><code>wp_localize_script( 'init_file', 'slider_option', $config_array ); $config_array = array( ... 'onSliderEnd' =&gt; $callback, ... ); </code></pre> <p>On the initialize jQuery file:</p> <pre><code>$('body').slider({ ... 'onSliderEnd': function(){ eval( slider_option.onSliderEnd; ); }, ... }); </code></pre> <p>Is this a safe way to use eval()? Any other suggestions? Or should I just not allow such an option?</p> <p>Thanks in advance for all your replies.</p>
[ { "answer_id": 224208, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 3, "selected": false, "text": "<p>You can change the name of your plugin, you just can't change the url slug of your plugin. Meaning, if you initially added a plugin to the repo and it was called \"Posts With Ad Thumbnails\" your url would be: <code>https://wordpress.org/plugins/posts-with-ad-thumbnails/</code></p>\n\n<p>After uploading your plugin, if you decide to change the name just edit your primary plugin file: <code>Plugin Name: name of plugin</code> to its new name and commit the change. Your plugin url will stay the same, but the display name will change.</p>\n\n<p>Ref: <a href=\"https://developer.wordpress.org/plugins/wordpress-org/plugin-developer-faq/#can-i-change-my-plugins-name\" rel=\"noreferrer\">https://developer.wordpress.org/plugins/wordpress-org/plugin-developer-faq/#can-i-change-my-plugins-name</a></p>\n" }, { "answer_id": 224211, "author": "Nabeel Khan", "author_id": 57389, "author_profile": "https://wordpress.stackexchange.com/users/57389", "pm_score": 0, "selected": false, "text": "<p>The best way to sort it is contacting: [email protected]</p>\n\n<p>I'm not sure that they'll change the url though.</p>\n\n<p>Regarding name of the plugin, simply change it through the php file header and also from the readme.txt file of your plugin.</p>\n" } ]
2016/04/20
[ "https://wordpress.stackexchange.com/questions/224219", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92661/" ]
I'll be brief and hope I can explain my scenario correctly. Here's my scenario. The jQuery slider plugin has an anonymous callback method. I would like to give the Admin the ability to create a function for that callback method. So from the plugin's add/edit pages the admin has a textarea to input the jQuery code. Now the textarea input gets save to the database and when it's passed using the wp\_localize\_script() it gets pass as a string that does not get recognize as a Javascript/jQuery code. So far, I have only being able to make it work using eval() in order for it to be recognize and to run as a Javascript/jQuery function. On the Admin page: `<textarea id="callback" name="callback" rows="10" ><?php echo $callback; ?></textarea>` On the wp\_localize\_script() array: ``` wp_localize_script( 'init_file', 'slider_option', $config_array ); $config_array = array( ... 'onSliderEnd' => $callback, ... ); ``` On the initialize jQuery file: ``` $('body').slider({ ... 'onSliderEnd': function(){ eval( slider_option.onSliderEnd; ); }, ... }); ``` Is this a safe way to use eval()? Any other suggestions? Or should I just not allow such an option? Thanks in advance for all your replies.
You can change the name of your plugin, you just can't change the url slug of your plugin. Meaning, if you initially added a plugin to the repo and it was called "Posts With Ad Thumbnails" your url would be: `https://wordpress.org/plugins/posts-with-ad-thumbnails/` After uploading your plugin, if you decide to change the name just edit your primary plugin file: `Plugin Name: name of plugin` to its new name and commit the change. Your plugin url will stay the same, but the display name will change. Ref: <https://developer.wordpress.org/plugins/wordpress-org/plugin-developer-faq/#can-i-change-my-plugins-name>
224,257
<pre><code>$new_post = array( 'post_title' =&gt; $title, 'post_content' =&gt; $description, 'post_category' =&gt; array($_POST['cat']), // Usable for custom taxonomies too 'tags_input' =&gt; array($tags), 'post_status' =&gt; 'publish', // Choose: publish, preview, future, draft, etc. 'post_type' =&gt; 'my_custom_type' ); wp_insert_post($new_post); </code></pre> <p>How can I get the post id? Is it automatically generated? How can I show it before the form is posted? I'm trying to create a frontend form where I show to the user the post id is going to be created. Like "Hey man, you're posting the article nr # <code>&lt;?php echo $postID;?&gt;</code>". Is there a way or I'm totally out of mind? Thanks in advance.</p>
[ { "answer_id": 224267, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 3, "selected": false, "text": "<p>Check the <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"noreferrer\">documentation</a>:</p>\n\n<blockquote>\n <p>Return: (int|WP_Error) The post ID on success. The value 0 or WP_Error on failure.</p>\n</blockquote>\n\n<p>Thus:</p>\n\n<pre><code>$result = wp_insert_post( $data );\n\nif ( $result &amp;&amp; ! is_wp_error( $result ) ) {\n $post_id = $result;\n // Do something else\n}\n</code></pre>\n" }, { "answer_id": 224274, "author": "André Gumieri", "author_id": 92469, "author_profile": "https://wordpress.stackexchange.com/users/92469", "pm_score": 4, "selected": true, "text": "<p>You'll have to do this in two steps. First, you will create a post in the draft mode, using wp_insert_post(). The wp_insert_post itself will return to you the ID of the inserted post:</p>\n<pre><code>&lt;?php\n$new_post = array(\n 'post_title' =&gt; 'Draft title',\n 'post_status' =&gt; 'draft'\n 'post_type' =&gt; 'my_custom_type'\n);\n$postId = wp_insert_post($new_post);\n?&gt;\n\n&lt;form method=&quot;post&quot; action=&quot;your-action.php&quot;&gt;\n &lt;p&gt;Hey! You are creating the post #&lt;?php echo $postId; ?&gt;&lt;/p&gt;\n &lt;input type=&quot;hidden&quot; name=&quot;draft_id&quot; value=&quot;&lt;?php echo $postId; ?&gt;&quot;&gt;\n ...\n&lt;/form&gt;\n</code></pre>\n<p>After that, in the action page, you will get the draft id and update the post. You'll use wp_update_post informing the draft ID.</p>\n<pre><code>&lt;?php\n$draftId = $_POST['draft_id'];\n...\n\n$updated_post = array(\n 'ID' =&gt; $draftId,\n 'post_title' =&gt; $title,\n ...\n 'post_status' =&gt; 'publish', // Now it's public\n 'post_type' =&gt; 'my_custom_type'\n);\nwp_update_post($updated_post);\n?&gt;\n</code></pre>\n<p>Hope it helps :)</p>\n" } ]
2016/04/20
[ "https://wordpress.stackexchange.com/questions/224257", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92398/" ]
``` $new_post = array( 'post_title' => $title, 'post_content' => $description, 'post_category' => array($_POST['cat']), // Usable for custom taxonomies too 'tags_input' => array($tags), 'post_status' => 'publish', // Choose: publish, preview, future, draft, etc. 'post_type' => 'my_custom_type' ); wp_insert_post($new_post); ``` How can I get the post id? Is it automatically generated? How can I show it before the form is posted? I'm trying to create a frontend form where I show to the user the post id is going to be created. Like "Hey man, you're posting the article nr # `<?php echo $postID;?>`". Is there a way or I'm totally out of mind? Thanks in advance.
You'll have to do this in two steps. First, you will create a post in the draft mode, using wp\_insert\_post(). The wp\_insert\_post itself will return to you the ID of the inserted post: ``` <?php $new_post = array( 'post_title' => 'Draft title', 'post_status' => 'draft' 'post_type' => 'my_custom_type' ); $postId = wp_insert_post($new_post); ?> <form method="post" action="your-action.php"> <p>Hey! You are creating the post #<?php echo $postId; ?></p> <input type="hidden" name="draft_id" value="<?php echo $postId; ?>"> ... </form> ``` After that, in the action page, you will get the draft id and update the post. You'll use wp\_update\_post informing the draft ID. ``` <?php $draftId = $_POST['draft_id']; ... $updated_post = array( 'ID' => $draftId, 'post_title' => $title, ... 'post_status' => 'publish', // Now it's public 'post_type' => 'my_custom_type' ); wp_update_post($updated_post); ?> ``` Hope it helps :)
224,278
<p>I am in trouble. I have a travel site...I have created a page where users can write a form to insert their houses.</p> <p>The houses are of course a custom post type.</p> <p>This is a piece of my code:</p> <pre><code>... some validation here if ($idarticolo = wp_insert_post($post)) { //lingua global $polylang; $lang = pll_current_language(); $polylang-&gt;set_post_language($idarticolo, $lang); ... </code></pre> <p>everything works fine, the house is inserted in my current language; but when I try to translate this post from admin panel, I get an error. </p> <p>The post is not translated, and no language is detected.</p> <p>Please help!!!...many thanks in advance!</p> <p>M.:)</p>
[ { "answer_id": 224280, "author": "RiaanP", "author_id": 66345, "author_profile": "https://wordpress.stackexchange.com/users/66345", "pm_score": 3, "selected": true, "text": "<p>Apparently Polylang has an undocumented pll_save_post API method. See here: <a href=\"https://wordpress.org/support/topic/programmatically-set-post-language-and-translations\" rel=\"nofollow\">https://wordpress.org/support/topic/programmatically-set-post-language-and-translations</a></p>\n" }, { "answer_id": 224358, "author": "Mauro", "author_id": 92701, "author_profile": "https://wordpress.stackexchange.com/users/92701", "pm_score": 2, "selected": false, "text": "<p>Ok Riaan,</p>\n\n<p>thank you for your reply. </p>\n\n<p>I solved in this way (maybe can be helpful):</p>\n\n<pre><code>if ($idarticolo = wp_insert_post($post, true)) {\n\n // inserisco l'articolo nelle altre lingue: En Es Fr\n $idarticoloEn = wp_insert_post($post, true);\n $idarticoloEs = wp_insert_post($post, true);\n $idarticoloFr = wp_insert_post($post, true);\n\n $polylang-&gt;model-&gt;set_post_language($idarticolo, 'it');\n $polylang-&gt;model-&gt;set_post_language($idarticoloEn, 'en');\n $polylang-&gt;model-&gt;set_post_language($idarticoloEs, 'es');\n $polylang-&gt;model-&gt;set_post_language($idarticoloFr, 'fr');\n\n $polylang-&gt;model-&gt;save_translations('post', $idarticolo, array('en' =&gt; $idarticoloEn));\n $polylang-&gt;model-&gt;save_translations('post', $idarticolo, array('es' =&gt; $idarticoloEs));\n $polylang-&gt;model-&gt;save_translations('post', $idarticolo, array('fr' =&gt; $idarticoloFr));\n</code></pre>\n\n<p>I insert the post in italian, and then I create the corresponding translations in the the other languages. </p>\n\n<p>Thank you again for your help!</p>\n\n<p>M :)</p>\n" }, { "answer_id": 338147, "author": "Hanafi", "author_id": 168264, "author_profile": "https://wordpress.stackexchange.com/users/168264", "pm_score": 2, "selected": false, "text": "<p>Update <a href=\"https://wordpress.stackexchange.com/questions/224278/polylang-translation-of-a-custom-post-created-by-wp-insert-post/224358#224358\">@Mauro's answer</a> based Polylang version 2.5.3.</p>\n\n<pre><code>....\n if ($idarticolo = wp_insert_post($post, true)) {\n $posts = array(\n 'en' =&gt; '',\n 'es' =&gt; '',\n 'fr' =&gt; '',\n );\n\n // inserisco l'articolo nelle altre lingue: En Es Fr\n foreach ($posts as $language =&gt; $value) {\n $posts[$language] = wp_insert_post($post, true);\n }\n\n if (function_exists('pll_set_post_language') \n &amp;&amp; function_exists('pll_save_post_translations')) {\n\n pll_set_post_language($idarticolo, 'it');\n foreach ($posts as $language =&gt; $value) {\n pll_set_post_language($value, $language);\n }\n\n pll_save_post_translations(array_merge(array($idarticolo), $posts));\n }\n....\n</code></pre>\n\n<p>To set term language, use <code>pll_set_term_language</code>.</p>\n\n<p>To save term translations, use <code>pll_save_term_translations</code>. </p>\n" } ]
2016/04/20
[ "https://wordpress.stackexchange.com/questions/224278", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92701/" ]
I am in trouble. I have a travel site...I have created a page where users can write a form to insert their houses. The houses are of course a custom post type. This is a piece of my code: ``` ... some validation here if ($idarticolo = wp_insert_post($post)) { //lingua global $polylang; $lang = pll_current_language(); $polylang->set_post_language($idarticolo, $lang); ... ``` everything works fine, the house is inserted in my current language; but when I try to translate this post from admin panel, I get an error. The post is not translated, and no language is detected. Please help!!!...many thanks in advance! M.:)
Apparently Polylang has an undocumented pll\_save\_post API method. See here: <https://wordpress.org/support/topic/programmatically-set-post-language-and-translations>
224,288
<p>I want to add bootstrap img-responsive and img-rounded classes to avatar image when displaying one. But for some reason the class is not displayed when using <code>get_avatar</code>.</p> <p>By WordPress codex there is an attributes list that you can use in <code>get_avatar</code> to alter the function but my doesn't pickup class array list.</p> <p>Here is current code that i use.</p> <pre><code>get_avatar( $current_user-&gt;user_email, 128, null, null, array('class' =&gt; array('img-responsive', 'img-rounded') ) ); </code></pre> <p>By explanation last parameter is arguments array in which you can use <code>size</code> , <code>height</code> , <code>width</code> etc... among those is <code>class</code> which can be array or string.</p> <p>So i tried a few combinations</p> <pre><code>$args = array( 'class' =&gt; 'img-responsive img-rounded' ); get_avatar( $current_user-&gt;user_email, 128, null, null, $args ); </code></pre> <p>I also tried</p> <pre><code>$args = array( 'class' =&gt; array( 'img-responsive', 'img-rounded'); ); </code></pre> <p>But for some reason class is not accepted.</p>
[ { "answer_id": 261318, "author": "gavsiu", "author_id": 7466, "author_profile": "https://wordpress.stackexchange.com/users/7466", "pm_score": 3, "selected": false, "text": "<p>I had this problem, too. Here's the solution for version 4.7.3 if anyone comes across this.</p>\n\n<pre><code>get_avatar( $id_or_email = get_the_author_meta( 'user_email' ), $size = '60', $default, $alt, $args = array( 'class' =&gt; array( 'd-block', 'mx-auto' ) ) );\n</code></pre>\n\n<p>or shorter version</p>\n\n<pre><code>get_avatar( get_the_author_meta( 'user_email' ), '60', $default, $alt, array( 'class' =&gt; array( 'd-block', 'mx-auto' ) ) );\n</code></pre>\n\n<p>For some reason, all the parameters have to be present or it doesn't work.</p>\n\n<p>This method, unlike the functions.php method, will not alter get_avatar globally. So you can have different classes like \"post-author\" or \"comments-author\".</p>\n" }, { "answer_id": 329895, "author": "Pial Arifur Rahman", "author_id": 162025, "author_profile": "https://wordpress.stackexchange.com/users/162025", "pm_score": 0, "selected": false, "text": "<p>Try this one..</p>\n\n<pre><code>&lt;?php echo get_avatar( get_the_author_meta('ID'), $args['image_size'], '', 'alt', array('class' =&gt; 'avatar_class') ); ?&gt;\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>&lt;?php echo get_avatar( get_the_author_meta('ID'), $args['96'], '', 'avatar', array('class' =&gt; 'myclass') ); ?&gt;\n</code></pre>\n" }, { "answer_id": 363185, "author": "Jeremy Richardson", "author_id": 185398, "author_profile": "https://wordpress.stackexchange.com/users/185398", "pm_score": 0, "selected": false, "text": "<p>Is there any chance you are using the plugin WP User Avatar. I have just run into this where it seems that it is filtering the get_avatar function but not passing the last $args argument through that would contain the class info.</p>\n\n<p>I'm going to start looking for a different solution to uploading custom avatars...</p>\n" } ]
2016/04/20
[ "https://wordpress.stackexchange.com/questions/224288", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/21135/" ]
I want to add bootstrap img-responsive and img-rounded classes to avatar image when displaying one. But for some reason the class is not displayed when using `get_avatar`. By WordPress codex there is an attributes list that you can use in `get_avatar` to alter the function but my doesn't pickup class array list. Here is current code that i use. ``` get_avatar( $current_user->user_email, 128, null, null, array('class' => array('img-responsive', 'img-rounded') ) ); ``` By explanation last parameter is arguments array in which you can use `size` , `height` , `width` etc... among those is `class` which can be array or string. So i tried a few combinations ``` $args = array( 'class' => 'img-responsive img-rounded' ); get_avatar( $current_user->user_email, 128, null, null, $args ); ``` I also tried ``` $args = array( 'class' => array( 'img-responsive', 'img-rounded'); ); ``` But for some reason class is not accepted.
I had this problem, too. Here's the solution for version 4.7.3 if anyone comes across this. ``` get_avatar( $id_or_email = get_the_author_meta( 'user_email' ), $size = '60', $default, $alt, $args = array( 'class' => array( 'd-block', 'mx-auto' ) ) ); ``` or shorter version ``` get_avatar( get_the_author_meta( 'user_email' ), '60', $default, $alt, array( 'class' => array( 'd-block', 'mx-auto' ) ) ); ``` For some reason, all the parameters have to be present or it doesn't work. This method, unlike the functions.php method, will not alter get\_avatar globally. So you can have different classes like "post-author" or "comments-author".
224,296
<p>Is there a way to remove all query arg parameter in the URL added via <code>add_query_arg();</code> without knowing the query key available for removal?</p> <p>I'm looking for this kind of function <code>remove_query_arg_all();</code> currently I'm removing the query_arg via preg_match REQUEST_URI, but not sure if it will cause any problem in the future.</p>
[ { "answer_id": 224300, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 4, "selected": true, "text": "<p>You can explode URL by <code>?</code> and take the first part:</p>\n\n<pre><code>$url = explode( '?', esc_url_raw( add_query_arg( array() ) ) );\n\n$no_query_args = $url[0];\n</code></pre>\n" }, { "answer_id": 355802, "author": "Simeon Griggs", "author_id": 180646, "author_profile": "https://wordpress.stackexchange.com/users/180646", "pm_score": 1, "selected": false, "text": "<p>You can do this in one line if your aim is to remove all of the params from the current <code>$_GET</code></p>\n\n<pre><code>remove_query_arg(array_keys($_GET))\n</code></pre>\n" } ]
2016/04/20
[ "https://wordpress.stackexchange.com/questions/224296", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10997/" ]
Is there a way to remove all query arg parameter in the URL added via `add_query_arg();` without knowing the query key available for removal? I'm looking for this kind of function `remove_query_arg_all();` currently I'm removing the query\_arg via preg\_match REQUEST\_URI, but not sure if it will cause any problem in the future.
You can explode URL by `?` and take the first part: ``` $url = explode( '?', esc_url_raw( add_query_arg( array() ) ) ); $no_query_args = $url[0]; ```
224,312
<p><strong>Hello,</strong></p> <p>I have a 'Custom Post Type' with 8 taxonomies and I'm pretending display a list with only 6 taxonomies and the no empties terms of each one and hide 2 taxonomies.</p> <p>My current code displays all taxonomies with all terms hiding the empties one but I can not get how to hide the two taxonomies I want.</p> <p>This is my code:</p> <pre><code> &lt;? php $args = array( 'public' =&gt; true, '_builtin' =&gt; false ); // $output = 'names'; // or objects // $operator = 'and'; // 'and' or 'or' // $taxonomies = get_taxonomies( $args, $output, $operator ); $object = 'my-cpt-name'; $output = 'names'; $taxonomies = get_object_taxonomies( $object, $output ); if ( $taxonomies ) { foreach ( $taxonomies as $taxonomy ) { echo '&lt;h3&gt;' . $taxonomy . '&lt;/h3&gt;'; $args = array( 'hide_empty=0' ); $terms = get_terms( $taxonomy, $args ); if ( ! empty( $terms ) &amp;&amp; ! is_wp_error( $terms ) ) { $count = count( $terms ); $i = 0; $term_list = '&lt;ul class="term-list"&gt;'; foreach ( $terms as $term ) { $i++; $term_list .= '&lt;li&gt;&lt;a href="' . esc_url( get_term_link( $term ) ) . '" &gt;' . $term-&gt;name . '&lt;/a&gt;&lt;/li&gt;'; if ( $count != $i ) { } else { $term_list .= '&lt;/ul&gt;'; } } echo $term_list; } } } ?&gt; </code></pre> <p>I have set up the 'public' taxonomy $arg as 'false' but doesn't work.</p> <pre><code>$args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; false, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_tagcloud' =&gt; true, ); </code></pre> <p>And also, how could I display the taxonomy name instead of the taxonomy slug on <code>echo '&lt;h3&gt;' . $taxonomy . '&lt;/h3&gt;';</code></p>
[ { "answer_id": 224315, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 2, "selected": false, "text": "<p>Try this: </p>\n\n<pre><code>&lt;?php\n$object = 'post';\n$output = 'objects';\n$taxonomies = get_object_taxonomies( $object, $output );\n$exclude = array( 'post_tag', 'post_format' );\n\nif ( $taxonomies ) {\n\n foreach ( $taxonomies as $taxonomy ) {\n\n if( in_array( $taxonomy-&gt;name, $exclude ) ) {\n continue;\n }\n\n $terms = get_terms( array(\n 'taxonomy' =&gt; $taxonomy-&gt;name,\n 'hide_empty' =&gt; true,\n ) );\n\n if ( ! empty( $terms ) &amp;&amp; ! is_wp_error( $terms ) ) {\n\n echo '&lt;h3&gt;' . $taxonomy-&gt;label . '&lt;/h3&gt;'; \n\n $term_list = '&lt;ul class=\"term-list\"&gt;';\n\n foreach ( $terms as $term ) {\n $term_list .= '&lt;li&gt;&lt;a href=\"' . esc_url( get_term_link( $term ) ) . '\" &gt;' . $term-&gt;name . '&lt;/a&gt;&lt;/li&gt;'; \n }\n\n $term_list .= '&lt;/ul&gt;';\n\n echo $term_list;\n }\n\n }\n\n}\n?&gt;\n</code></pre>\n\n<p>For this example I set up some parameters:</p>\n\n<ul>\n<li>Post type we're searching on: <code>$object = 'post';</code></li>\n<li>Taxonomies we want to exclude: <code>$exclude = array( 'post_tag', 'post_format' );</code></li>\n</ul>\n\n<p>Then we get all associated taxonomies and loop through them. While we loop through them, we check each taxonomy against our exclude array and skip it if applicable. </p>\n\n<p>Then we grab all the terms from each taxonomy and build list of links.</p>\n" }, { "answer_id": 224717, "author": "andresgl", "author_id": 65640, "author_profile": "https://wordpress.stackexchange.com/users/65640", "pm_score": 1, "selected": true, "text": "<p><strong>@darrinb</strong></p>\n\n<p>I have solved the problem. Your code helped me a lot although had a error. :)</p>\n\n<p>The error was getting the 'terms':</p>\n\n<pre><code>$terms = get_terms( array(\n 'taxonomy' =&gt; $taxonomy-&gt;name,\n 'hide_empty' =&gt; true,\n ) );\n</code></pre>\n\n<p>Following the <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\">codex</a>:</p>\n\n\n\n<p>The correct way is the following:</p>\n\n<pre><code>$arg = array(\n 'hide_empty' =&gt; true,\n );\n$terms = get_terms($taxonomy-&gt;name, $arg );\n</code></pre>\n\n<p>Thank you!</p>\n" } ]
2016/04/20
[ "https://wordpress.stackexchange.com/questions/224312", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65640/" ]
**Hello,** I have a 'Custom Post Type' with 8 taxonomies and I'm pretending display a list with only 6 taxonomies and the no empties terms of each one and hide 2 taxonomies. My current code displays all taxonomies with all terms hiding the empties one but I can not get how to hide the two taxonomies I want. This is my code: ``` <? php $args = array( 'public' => true, '_builtin' => false ); // $output = 'names'; // or objects // $operator = 'and'; // 'and' or 'or' // $taxonomies = get_taxonomies( $args, $output, $operator ); $object = 'my-cpt-name'; $output = 'names'; $taxonomies = get_object_taxonomies( $object, $output ); if ( $taxonomies ) { foreach ( $taxonomies as $taxonomy ) { echo '<h3>' . $taxonomy . '</h3>'; $args = array( 'hide_empty=0' ); $terms = get_terms( $taxonomy, $args ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) { $count = count( $terms ); $i = 0; $term_list = '<ul class="term-list">'; foreach ( $terms as $term ) { $i++; $term_list .= '<li><a href="' . esc_url( get_term_link( $term ) ) . '" >' . $term->name . '</a></li>'; if ( $count != $i ) { } else { $term_list .= '</ul>'; } } echo $term_list; } } } ?> ``` I have set up the 'public' taxonomy $arg as 'false' but doesn't work. ``` $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => false, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, ); ``` And also, how could I display the taxonomy name instead of the taxonomy slug on `echo '<h3>' . $taxonomy . '</h3>';`
**@darrinb** I have solved the problem. Your code helped me a lot although had a error. :) The error was getting the 'terms': ``` $terms = get_terms( array( 'taxonomy' => $taxonomy->name, 'hide_empty' => true, ) ); ``` Following the [codex](https://developer.wordpress.org/reference/functions/get_terms/): The correct way is the following: ``` $arg = array( 'hide_empty' => true, ); $terms = get_terms($taxonomy->name, $arg ); ``` Thank you!
224,332
<p>I'm trying to output all of the fields in the json result but seem to be using the object incorrectly. I want to add author meta fields to the post endpoint.</p> <p>This doesn't work</p> <pre><code> function slug_show_author_meta( $object, $field_name, $request ) { return get_the_author_meta( $object[ 'id' ], $field_name ); } </code></pre> <p>This does but only gives me one field</p> <pre><code> function slug_show_author_meta( ) { return get_the_author_meta('user_nicename'); } </code></pre> <p>Ideally I'd just like to get user_nicenaem, user_email, display_name, nicename, first_name and last_name. Thanks!</p>
[ { "answer_id": 224336, "author": "wpclevel", "author_id": 92212, "author_profile": "https://wordpress.stackexchange.com/users/92212", "pm_score": 3, "selected": true, "text": "<p>This should work:\n</p>\n\n<pre><code>function wpse_20160421_get_author_meta($object, $field_name, $request) {\n\n $user_data = get_userdata($object['author']); // get user data from author ID.\n\n $array_data = (array)($user_data-&gt;data); // object to array conversion.\n\n $array_data['first_name'] = get_user_meta($object['author'], 'first_name', true);\n $array_data['last_name'] = get_user_meta($object['author'], 'last_name', true);\n\n // prevent user enumeration.\n unset($array_data['user_login']);\n unset($array_data['user_pass']);\n unset($array_data['user_activation_key']);\n\n return array_filter($array_data);\n\n}\n\nfunction wpse_20160421_register_author_meta_rest_field() {\n\n register_rest_field('post', 'author_meta', array(\n 'get_callback' =&gt; 'wpse_20160421_get_author_meta',\n 'update_callback' =&gt; null,\n 'schema' =&gt; null,\n ));\n\n}\nadd_action('rest_api_init', 'wpse_20160421_register_author_meta_rest_field');\n</code></pre>\n" }, { "answer_id": 224341, "author": "Mr Brimm", "author_id": 19251, "author_profile": "https://wordpress.stackexchange.com/users/19251", "pm_score": 0, "selected": false, "text": "<p>This did the trick thanks to @Dan for pointing me in the right direction.</p>\n\n<pre><code> function slug_show_author_meta( $object ) {\n $post_author = (int) $object['author'];\n $array_data = array();\n\n $array_data['login'] = get_the_author_meta('login');\n\n $array_data['email'] = get_the_author_meta('email');\n\n $array_data['user_nicename'] = get_the_author_meta('user_nicename');\n\n $array_data['first_name'] = get_user_meta($post_author, 'first_name', true);\n\n $array_data['last_name'] = get_user_meta($post_author, 'last_name', true);\n\n $array_data['nickname'] = get_user_meta($post_author, 'nickname', true);\n\n return array_filter($array_data);\n }\n</code></pre>\n\n<p>it returns</p>\n\n<pre><code> \"post_author_meta\": {\n \"login\": \"billy\"\n \"email\": \"[email protected]\"\n \"user_nicename\": \"billy\"\n \"first_name\": \"Billy\"\n \"last_name\": \"Boy\"\n \"nickname\": \"billy\"\n }\n</code></pre>\n" }, { "answer_id": 237146, "author": "Gecko Room", "author_id": 28421, "author_profile": "https://wordpress.stackexchange.com/users/28421", "pm_score": 2, "selected": false, "text": "<p>This worked for me:</p>\n\n<pre><code>add_action( 'rest_api_init', 'user_puntuacio' );\n\nfunction user_puntuacio() {\n register_rest_field( 'user', 'puntuacio',\n array(\n 'get_callback' =&gt; 'get_user_puntuacio',\n 'update_callback' =&gt; null,\n 'schema' =&gt; null,\n )\n );\n}\n\n\nfunction get_user_puntuacio( $object, $field_name, $request ) {\n return get_user_meta( $object[ 'id' ], 'puntuacio', true );\n}\n</code></pre>\n\n<p>Note that 'puntuacio' is the custom user meta I wanted to add.</p>\n" } ]
2016/04/21
[ "https://wordpress.stackexchange.com/questions/224332", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/19251/" ]
I'm trying to output all of the fields in the json result but seem to be using the object incorrectly. I want to add author meta fields to the post endpoint. This doesn't work ``` function slug_show_author_meta( $object, $field_name, $request ) { return get_the_author_meta( $object[ 'id' ], $field_name ); } ``` This does but only gives me one field ``` function slug_show_author_meta( ) { return get_the_author_meta('user_nicename'); } ``` Ideally I'd just like to get user\_nicenaem, user\_email, display\_name, nicename, first\_name and last\_name. Thanks!
This should work: ``` function wpse_20160421_get_author_meta($object, $field_name, $request) { $user_data = get_userdata($object['author']); // get user data from author ID. $array_data = (array)($user_data->data); // object to array conversion. $array_data['first_name'] = get_user_meta($object['author'], 'first_name', true); $array_data['last_name'] = get_user_meta($object['author'], 'last_name', true); // prevent user enumeration. unset($array_data['user_login']); unset($array_data['user_pass']); unset($array_data['user_activation_key']); return array_filter($array_data); } function wpse_20160421_register_author_meta_rest_field() { register_rest_field('post', 'author_meta', array( 'get_callback' => 'wpse_20160421_get_author_meta', 'update_callback' => null, 'schema' => null, )); } add_action('rest_api_init', 'wpse_20160421_register_author_meta_rest_field'); ```
224,347
<p>I connect a lot of my posts to my new ones, and that is probably why I keep getting self pingbacks. Besides a plugin, is there a script I can use to get rid of this? </p>
[ { "answer_id": 224350, "author": "Sumeet Gohel", "author_id": 92729, "author_profile": "https://wordpress.stackexchange.com/users/92729", "pm_score": 3, "selected": true, "text": "<p>You could try this by putting code in functions.php in your theme.</p>\n\n<pre><code>function no_self_ping( &amp;$links ) {\n$home = get_option( 'home' );\nforeach ( $links as $l =&gt; $link )\n if ( 0 === strpos( $link, $home ) )\n unset($links[$l]);\n}\nadd_action( 'pre_ping', 'no_self_ping' );\n</code></pre>\n\n<p>Hope this helpful to you. </p>\n" }, { "answer_id": 226970, "author": "cogdog", "author_id": 14945, "author_profile": "https://wordpress.stackexchange.com/users/14945", "pm_score": 1, "selected": false, "text": "<p>I used a no trackback plugin for a few years (and I forget which one, there are a few available); it did seem silly to ping myself. Then I decided it was more like a way to connect posts, and stopped using it.</p>\n\n<p>For a small amount of code, it's probably not much of a tradeoff between plugin or to try the code above. As an alternative to changing the theme, for a few projects especially on multisite where I do not want to alter themes others might use, I have used the <a href=\"https://wordpress.org/plugins/my-custom-functions/\" rel=\"nofollow\">My Custom Functions plugin</a> to add small bits of code w/o having to mod functions.php</p>\n" } ]
2016/04/21
[ "https://wordpress.stackexchange.com/questions/224347", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68815/" ]
I connect a lot of my posts to my new ones, and that is probably why I keep getting self pingbacks. Besides a plugin, is there a script I can use to get rid of this?
You could try this by putting code in functions.php in your theme. ``` function no_self_ping( &$links ) { $home = get_option( 'home' ); foreach ( $links as $l => $link ) if ( 0 === strpos( $link, $home ) ) unset($links[$l]); } add_action( 'pre_ping', 'no_self_ping' ); ``` Hope this helpful to you.
224,360
<p>How to i foreach the post title like below. this is what i want below</p> <pre><code>function get_all_post_for_search() { return array ( array( 'name' =&gt; "Hello Project", 'thumb' =&gt; '/wp-content/uploads/2016/03/photo-1442473483905-95eb436675f1.jpeg', 'desc' =&gt; 'Lorem ipsum dolor sit amet, consectetur adipisicing elit..' ), array( 'name' =&gt; "Another Project", 'thumb' =&gt; '/wp-content/uploads/2016/03/photo-1449024540548-94f5d5a59230-1.jpeg', 'desc' =&gt; 'Lorem ipsum dolor sit amet, consectetur adipisicing elit..' ) ); } </code></pre> <p>this is my code</p> <pre><code>function all_post_data(){ $args = array ( 'post_type' =&gt; 'post', 'pagination' =&gt; FALSE, 'suppress_filters' =&gt; FALSE ); $query = new WP_Query( $args ); if($query-&gt;have_posts()): while($query-&gt;have_posts()): $query-&gt;the_post(); $post_id = get_the_id(); $the_title = get_the_title(); $thumbs = get_post_thumbnail_id(); $des = get_the_content(); $search_data = []; $img_url = $thumb['url']; if(is_array($thumb) &amp;&amp; $img_url){ $search_data[] = array( 'name' =&gt; $the_title, 'thumb' =&gt; $img_url, 'desc' =&gt; $des ); } endwhile; endif; wp_reset_postdata(); var_dump($search_data); } </code></pre>
[ { "answer_id": 224365, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 1, "selected": false, "text": "<p>Your code has many errors:-</p>\n\n<ul>\n<li><code>$thumbs</code> isn't used anywhere.</li>\n<li><code>$img_url = $thumb['url'];</code> undefined variable</li>\n<li><code>if(is_array($thumb) &amp;&amp; $img_url)</code> always <code>false</code> because of second point.</li>\n<li><code>$search_data = [];</code> should be outside of loop.</li>\n</ul>\n\n<p>Check the correct part of code</p>\n\n<pre><code>$search_data = [];\nif($query-&gt;have_posts()):\n while($query-&gt;have_posts()):\n $query-&gt;the_post();\n\n $img_url = get_the_post_thumbnail_url();\n\n if(!empty($img_url)){\n $search_data[] = array(\n 'name' =&gt; get_the_title(),\n 'thumb' =&gt; $img_url,\n 'desc' =&gt; get_the_content()\n );\n } \n endwhile;\nendif;\n</code></pre>\n\n<blockquote>\n <p>NOTE: <code>get_the_post_thumbnail_url()</code> is only available from WordPress\n 4.4</p>\n</blockquote>\n" }, { "answer_id": 224366, "author": "Mohamed Rihan", "author_id": 85768, "author_profile": "https://wordpress.stackexchange.com/users/85768", "pm_score": -1, "selected": true, "text": "<p>working code</p>\n\n<pre><code>function list_post_data(){\n $args=\"SELECT * FROM wp_posts WHERE wp_posts.`post_type` = 'post' AND wp_posts.`post_status` = 'publish'\";\n\n $args = array(\n 'post_type' =&gt; 'post'\n );\n\n $loop = new WP_Query( $args );\n\n $array = array();\n\n while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n\n global $post;\n $url = wp_get_attachment_url( get_post_thumbnail_id($post-&gt;ID) );\n $array[] = array(\n //'id' =&gt; get_the_ID(),\n 'name' =&gt; get_the_title(),\n 'thumb' =&gt; $url,\n 'desc' =&gt; get_the_content()\n );\n\n endwhile;\n\n // wp_reset_query();\n ob_clean();\n //echo json_encode($array);\n var_dump($array);\n exit();\n}\n</code></pre>\n\n<p>result is </p>\n\n<pre><code>array (size=2)\n 0 =&gt; \n array (size=3)\n 'name' =&gt; string 'test post' (length=9)\n 'thumb' =&gt; boolean false\n 'desc' =&gt; string 'dfgrgsrga' (length=9)\n 1 =&gt; \n array (size=3)\n 'name' =&gt; string 'Hello world!' (length=12)\n 'thumb' =&gt; string 'http://lfigp-new.dev/wp-content/uploads/2016/03/valentine-cake_1x.png' (length=69)\n 'desc' =&gt; string 'Welcome to WordPress. This is your first post. Edit or delete it, then start writing!' (length=85)\n</code></pre>\n" } ]
2016/04/21
[ "https://wordpress.stackexchange.com/questions/224360", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85768/" ]
How to i foreach the post title like below. this is what i want below ``` function get_all_post_for_search() { return array ( array( 'name' => "Hello Project", 'thumb' => '/wp-content/uploads/2016/03/photo-1442473483905-95eb436675f1.jpeg', 'desc' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit..' ), array( 'name' => "Another Project", 'thumb' => '/wp-content/uploads/2016/03/photo-1449024540548-94f5d5a59230-1.jpeg', 'desc' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit..' ) ); } ``` this is my code ``` function all_post_data(){ $args = array ( 'post_type' => 'post', 'pagination' => FALSE, 'suppress_filters' => FALSE ); $query = new WP_Query( $args ); if($query->have_posts()): while($query->have_posts()): $query->the_post(); $post_id = get_the_id(); $the_title = get_the_title(); $thumbs = get_post_thumbnail_id(); $des = get_the_content(); $search_data = []; $img_url = $thumb['url']; if(is_array($thumb) && $img_url){ $search_data[] = array( 'name' => $the_title, 'thumb' => $img_url, 'desc' => $des ); } endwhile; endif; wp_reset_postdata(); var_dump($search_data); } ```
working code ``` function list_post_data(){ $args="SELECT * FROM wp_posts WHERE wp_posts.`post_type` = 'post' AND wp_posts.`post_status` = 'publish'"; $args = array( 'post_type' => 'post' ); $loop = new WP_Query( $args ); $array = array(); while ( $loop->have_posts() ) : $loop->the_post(); global $post; $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); $array[] = array( //'id' => get_the_ID(), 'name' => get_the_title(), 'thumb' => $url, 'desc' => get_the_content() ); endwhile; // wp_reset_query(); ob_clean(); //echo json_encode($array); var_dump($array); exit(); } ``` result is ``` array (size=2) 0 => array (size=3) 'name' => string 'test post' (length=9) 'thumb' => boolean false 'desc' => string 'dfgrgsrga' (length=9) 1 => array (size=3) 'name' => string 'Hello world!' (length=12) 'thumb' => string 'http://lfigp-new.dev/wp-content/uploads/2016/03/valentine-cake_1x.png' (length=69) 'desc' => string 'Welcome to WordPress. This is your first post. Edit or delete it, then start writing!' (length=85) ```
224,371
<p>I have a CPT called 'experts', that has been created in a theme I bought, and I can't find out where nor where to change it. I need to change a parameter to 'with_front' => false Because my general permaling structure goes with /blog and I do'nt want experts to be in /blog/experts. Is there a way I could do that adding something in the functions file? I have tried this (<a href="https://wordpress.stackexchange.com/questions/156378/how-to-set-with-front-false-to-a-plugin-generated-cpt">How to set &quot;with_front&#39;=&gt;false&quot; to a plugin-generated cpt?</a>) and various things, but could not get it to work. Thanks :) </p>
[ { "answer_id": 224376, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>You could try the newly <a href=\"https://github.com/WordPress/WordPress/blob/a47fa4f1970996a2aa041ea53a37c4918065cc4b/wp-includes/post.php#L1009-L1018\" rel=\"noreferrer\"><code>register_post_type_args</code></a> filter to adjust it. </p>\n\n<p>Here's an untested example:</p>\n\n<pre><code>/**\n * Set 'with_front' to false for the 'experts' post type.\n */\nadd_filter( 'register_post_type_args', function( $args, $post_type )\n{\n if( 'teachers' === $post_type &amp;&amp; is_array( $args ) )\n $args['rewrite']['with_front'] = false;\n\n return $args;\n}, 99, 2 );\n</code></pre>\n\n<p><strong>Updated</strong> with new info from @Agnes: the post type is <code>teachers</code> not <code>experts</code>.</p>\n" }, { "answer_id": 225048, "author": "Agnes", "author_id": 92741, "author_profile": "https://wordpress.stackexchange.com/users/92741", "pm_score": -1, "selected": false, "text": "<p>This solution works, added to parent theme functions.php:</p>\n\n<pre><code> add_filter( 'register_post_type_args', function( $args, $post_type )\n {\n $args['rewrite']['with_front'] = false;\n return $args;\n }, 10, 2 ); \n</code></pre>\n" }, { "answer_id": 228590, "author": "connectjax", "author_id": 95134, "author_profile": "https://wordpress.stackexchange.com/users/95134", "pm_score": 2, "selected": false, "text": "<p>Additionally, if the CPT has taxonomies associated with it, I've successfully used the following code to rewrite those as well:</p>\n\n<pre><code>/**\n * Set 'with_front' to false for the 'portfolio_category' post taxonomy.\n */\n\nadd_filter( 'register_taxonomy_args', function( $args, $taxonomy )\n {\n if( 'portfolio_category' === $taxonomy &amp;&amp; is_array( $args ) )\n $args['rewrite']['with_front'] = false;\n return $args;\n }, 99, 2 );\n</code></pre>\n\n<p>In case that is helpful to anyone.</p>\n" } ]
2016/04/21
[ "https://wordpress.stackexchange.com/questions/224371", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92741/" ]
I have a CPT called 'experts', that has been created in a theme I bought, and I can't find out where nor where to change it. I need to change a parameter to 'with\_front' => false Because my general permaling structure goes with /blog and I do'nt want experts to be in /blog/experts. Is there a way I could do that adding something in the functions file? I have tried this ([How to set "with\_front'=>false" to a plugin-generated cpt?](https://wordpress.stackexchange.com/questions/156378/how-to-set-with-front-false-to-a-plugin-generated-cpt)) and various things, but could not get it to work. Thanks :)
You could try the newly [`register_post_type_args`](https://github.com/WordPress/WordPress/blob/a47fa4f1970996a2aa041ea53a37c4918065cc4b/wp-includes/post.php#L1009-L1018) filter to adjust it. Here's an untested example: ``` /** * Set 'with_front' to false for the 'experts' post type. */ add_filter( 'register_post_type_args', function( $args, $post_type ) { if( 'teachers' === $post_type && is_array( $args ) ) $args['rewrite']['with_front'] = false; return $args; }, 99, 2 ); ``` **Updated** with new info from @Agnes: the post type is `teachers` not `experts`.
224,399
<p>I'm using <code>Root.io</code>'s <code>Trellis</code> workflow. </p> <p>I've encountered an error wherein I couldn't establish a connection via <code>ansible-playbook</code>.</p> <ol> <li><p>When I run <code>ansible-playbook server.yml -e env=staging</code> it throws me an error that the ssh connection cannot be established so I checked my <code>users.yml</code> file and saw a problem under the <code>keys</code> section:</p> <pre><code>- name: "{{ admin_user }}" groups: - sudo keys: - "{{ lookup('file', '~/.ssh/id_rsa.pub') }}" - https://github.com/dummyuser.keys </code></pre> <p>I realised I have an existing <code>id_rsa.pub</code> key but I didn't have it authorized on my server, I was using <code>https://github.com/dummyuser.keys</code> instead. So I removed that line </p> <pre><code>- "{{ lookup('file', '~/.ssh/id_rsa.pub') }}" </code></pre> <p>However the problem still persists. The response was:</p> <pre><code>fatal: [10.10.2.5]: UNREACHABLE! =&gt; { "changed": false, "msg": "Failed to connect to the host via ssh.", "unreachable": true } </code></pre> <p>Also why does the config point to the <code>public key</code> when we need the <code>private key</code> to login via ssh. I usually do </p> <pre><code>ssh -i ~/.ssh/private_key [email protected] </code></pre> <p>whenever I login to the server via ssh.</p></li> <li><p>I So I used another approach. specified the key on the cli this time</p> <pre><code>ansible-playbook server.yml -e env=staging -vvvv --key-file=~/.ssh/dummy_rsa </code></pre> <p>and the result was I was able to establish a connection:</p> <pre><code>&lt;10.10.2.5&gt; ESTABLISH SSH CONNECTION FOR USER: dummy_admin </code></pre> <p>But there was another error: it says <code>a password is required</code> here's the full message:</p> <pre><code>fatal: [10.10.2.5]: FAILED! =&gt; { "changed": false, "failed": true, "invocation": {"module_name": "setup"}, "module_stderr": "OpenSSH_6.9p1, LibreSSL 2.1.8\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 21: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug2: mux_client_hello_exchange: master version 4\r\ndebug3: mux_client_forwards: request forwardings: 0 local, 0 remote\r\ndebug3: mux_client_request_session: entering\r\ndebug3: mux_client_request_alive: entering\r\ndebug3: mux_client_request_alive: done pid = 85702\r\ndebug3: mux_client_request_session: session request sent\r\ndebug1: mux_client_request_session: master session id: 2\r\ndebug3: mux_client_read_packet: read header failed: Broken pipe\r\ndebug2: Received exit status from master 1\r\nShared connection to 10.10.2.5 closed.\r\n", "module_stdout": "sudo: a password is required\r\n", "msg": "MODULE FAILURE", "parsed": false } </code></pre> <p>I'm not sure why it is asking for a password I've already set it in my <code>group_vars/staging/vault.yml</code> here's the content of that:</p> <pre><code>vault_mysql_root_password: stagingpw vault_sudoer_passwords: dummy_admin: $6$rounds=656000$8DWzDN3KQkM9SjlF$DhxLkYaayplFmtj9q.EqzMDWmvlLNKsLU0GPL9E0P2EvkFQBsbjcMCXgWkug4a5E66PfwL4eZQXzMLkhXcPBk0 </code></pre></li> <li><p>So I finally got logged in using the command below:</p> <pre><code>ansible-playbook server.yml -e env=staging -vvvv --key-file=~/.ssh/dummy_rsa --ask-become-pass </code></pre> <p>after asking me for a password it works and provisions my server without problem.</p></li> </ol> <p>Can anyone give light to this? Am I missing something? Let me know if you need more details.</p>
[ { "answer_id": 224401, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 1, "selected": false, "text": "<p>You probably have not added your <strong>public</strong> key to the <code>authorized_keys</code> file <em>inside</em> the machine. You might also want to add your <strong>private</strong> key to your local SSH agent.</p>\n\n<ol>\n<li><p>Put your <strong>public</strong> key inside the server. Example for a key that is already on the server:</p>\n\n<pre><code># Add key directly on the box:\necho \"$(cat your_public_key)\" &gt;&gt; ~/.ssh/authorized_keys\n# Add key from local to remote:\nssh user@server \"echo \\\"$(cat your_public_key)\\\" &gt;&gt; ~/.ssh/authorized_keys\"\n</code></pre></li>\n<li><p>You need to add the <strong>private</strong> key to your agent</p>\n\n<pre><code># Start agent\neval \"$(ssh-agent -s)\"\n# Add private key\nssh-add ~/.ssh/your_private_key\n</code></pre></li>\n</ol>\n" }, { "answer_id": 224452, "author": "JohnnyQ", "author_id": 83285, "author_profile": "https://wordpress.stackexchange.com/users/83285", "pm_score": 3, "selected": true, "text": "<p>I've also posted this question on <a href=\"https://discourse.roots.io/t/failure-to-establish-connection-when-provisioning-via-ansible-playbook-server-yml/6518?u=jzarzoso\" rel=\"nofollow\">discourse</a> and <a href=\"https://discourse.roots.io/t/failure-to-establish-connection-when-provisioning-via-ansible-playbook-server-yml/6518/3?u=jzarzoso\" rel=\"nofollow\">@fullyint</a> has answered it in detail. So I'm just posting a link for the answer and some excerpt</p>\n\n<blockquote>\n <h1>Helping Ansible and ssh to find the necessary private key</h1>\n \n <p>This means that you are manually specifying the private key with each ssh command, and yes, the corollary of manually specifying the private key with every ansible-playbook command is to add the --private-key= or key-file= option. However, you could save yourself some hassle by enabling ssh and ansible-playbook commands to automatically find and use your desired private key file. One approach would be to add an entry to your ssh config file, specifying the IdentityFile to be used with Host 10.10.2.5. I'd recommend the alternative of loading the ~/.ssh/dummy_rsa into your ssh-agent, which can handle keys for you, trying multiple private keys when attempting a connection.<br>\n Make sure your ssh-agent is running: ssh-agent bash\n Add your key: ssh-add ~/.ssh/dummy_rsa\n If you're on mac, add the key to your Keychain: ssh-add -K ~/.ssh/dummy_rsa\n Now you should be able to run ssh commands without the -i option, and ansible-playbook commands without the --key-file= option because your ssh-agent will inform those commands of the various available private keys to try in making the ssh connections.</p>\n \n <h1>Reasons for the error \"sudo: a password is required\"</h1>\n \n <p>Of the tasks Trellis runs via the server.yml playbook, some require sudo. This is a non-issue when the playbook connects as root, but sometimes the playbook doesn't connect as root. If this initial connection attempt as root fails, it will fall back to connecting as the admin_user. This user must specify its sudo password via the option --ask-become-pass, as you discovered.<br>\n Maybe you already know why your connection as root failed, but here are some possibilities:<br>\n Maybe your remote is on AWS, where root is disabled by default, and your admin_user: ubuntu.<br>\n Maybe you've already successfully run server.yml with sshd_permit_root_login: false in group_vars/all/security.yml, so root is no longer allowed to log in via ssh (good security).\n Maybe the private key you are trying to use is not loaded on the remote in the root user's authorized_keys</p>\n</blockquote>\n" } ]
2016/04/21
[ "https://wordpress.stackexchange.com/questions/224399", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83285/" ]
I'm using `Root.io`'s `Trellis` workflow. I've encountered an error wherein I couldn't establish a connection via `ansible-playbook`. 1. When I run `ansible-playbook server.yml -e env=staging` it throws me an error that the ssh connection cannot be established so I checked my `users.yml` file and saw a problem under the `keys` section: ``` - name: "{{ admin_user }}" groups: - sudo keys: - "{{ lookup('file', '~/.ssh/id_rsa.pub') }}" - https://github.com/dummyuser.keys ``` I realised I have an existing `id_rsa.pub` key but I didn't have it authorized on my server, I was using `https://github.com/dummyuser.keys` instead. So I removed that line ``` - "{{ lookup('file', '~/.ssh/id_rsa.pub') }}" ``` However the problem still persists. The response was: ``` fatal: [10.10.2.5]: UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh.", "unreachable": true } ``` Also why does the config point to the `public key` when we need the `private key` to login via ssh. I usually do ``` ssh -i ~/.ssh/private_key [email protected] ``` whenever I login to the server via ssh. 2. I So I used another approach. specified the key on the cli this time ``` ansible-playbook server.yml -e env=staging -vvvv --key-file=~/.ssh/dummy_rsa ``` and the result was I was able to establish a connection: ``` <10.10.2.5> ESTABLISH SSH CONNECTION FOR USER: dummy_admin ``` But there was another error: it says `a password is required` here's the full message: ``` fatal: [10.10.2.5]: FAILED! => { "changed": false, "failed": true, "invocation": {"module_name": "setup"}, "module_stderr": "OpenSSH_6.9p1, LibreSSL 2.1.8\r\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: /etc/ssh/ssh_config line 21: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug2: fd 3 setting O_NONBLOCK\r\ndebug2: mux_client_hello_exchange: master version 4\r\ndebug3: mux_client_forwards: request forwardings: 0 local, 0 remote\r\ndebug3: mux_client_request_session: entering\r\ndebug3: mux_client_request_alive: entering\r\ndebug3: mux_client_request_alive: done pid = 85702\r\ndebug3: mux_client_request_session: session request sent\r\ndebug1: mux_client_request_session: master session id: 2\r\ndebug3: mux_client_read_packet: read header failed: Broken pipe\r\ndebug2: Received exit status from master 1\r\nShared connection to 10.10.2.5 closed.\r\n", "module_stdout": "sudo: a password is required\r\n", "msg": "MODULE FAILURE", "parsed": false } ``` I'm not sure why it is asking for a password I've already set it in my `group_vars/staging/vault.yml` here's the content of that: ``` vault_mysql_root_password: stagingpw vault_sudoer_passwords: dummy_admin: $6$rounds=656000$8DWzDN3KQkM9SjlF$DhxLkYaayplFmtj9q.EqzMDWmvlLNKsLU0GPL9E0P2EvkFQBsbjcMCXgWkug4a5E66PfwL4eZQXzMLkhXcPBk0 ``` 3. So I finally got logged in using the command below: ``` ansible-playbook server.yml -e env=staging -vvvv --key-file=~/.ssh/dummy_rsa --ask-become-pass ``` after asking me for a password it works and provisions my server without problem. Can anyone give light to this? Am I missing something? Let me know if you need more details.
I've also posted this question on [discourse](https://discourse.roots.io/t/failure-to-establish-connection-when-provisioning-via-ansible-playbook-server-yml/6518?u=jzarzoso) and [@fullyint](https://discourse.roots.io/t/failure-to-establish-connection-when-provisioning-via-ansible-playbook-server-yml/6518/3?u=jzarzoso) has answered it in detail. So I'm just posting a link for the answer and some excerpt > > Helping Ansible and ssh to find the necessary private key > ========================================================= > > > This means that you are manually specifying the private key with each ssh command, and yes, the corollary of manually specifying the private key with every ansible-playbook command is to add the --private-key= or key-file= option. However, you could save yourself some hassle by enabling ssh and ansible-playbook commands to automatically find and use your desired private key file. One approach would be to add an entry to your ssh config file, specifying the IdentityFile to be used with Host 10.10.2.5. I'd recommend the alternative of loading the ~/.ssh/dummy\_rsa into your ssh-agent, which can handle keys for you, trying multiple private keys when attempting a connection. > > Make sure your ssh-agent is running: ssh-agent bash > Add your key: ssh-add ~/.ssh/dummy\_rsa > If you're on mac, add the key to your Keychain: ssh-add -K ~/.ssh/dummy\_rsa > Now you should be able to run ssh commands without the -i option, and ansible-playbook commands without the --key-file= option because your ssh-agent will inform those commands of the various available private keys to try in making the ssh connections. > > > Reasons for the error "sudo: a password is required" > ==================================================== > > > Of the tasks Trellis runs via the server.yml playbook, some require sudo. This is a non-issue when the playbook connects as root, but sometimes the playbook doesn't connect as root. If this initial connection attempt as root fails, it will fall back to connecting as the admin\_user. This user must specify its sudo password via the option --ask-become-pass, as you discovered. > > Maybe you already know why your connection as root failed, but here are some possibilities: > > Maybe your remote is on AWS, where root is disabled by default, and your admin\_user: ubuntu. > > Maybe you've already successfully run server.yml with sshd\_permit\_root\_login: false in group\_vars/all/security.yml, so root is no longer allowed to log in via ssh (good security). > Maybe the private key you are trying to use is not loaded on the remote in the root user's authorized\_keys > > >
224,416
<p>So there is the following scenario.</p> <p>I add an action to clean logs from the database:</p> <pre><code>add_action( 'myplugin_clean_logs', array( 'MyPlugin_Logs', 'clean_logs' ) ); </code></pre> <p>Now I want to run this action periodically:</p> <pre><code>wp_schedule_event( current_time( 'timestamp' ), 'daily', 'myplugin_clean_logs' ); </code></pre> <p>and execute it manually:</p> <pre><code>do_action( 'myplugin_clean_logs' ); </code></pre> <p>The method <code>MyPlugin_Logs::clean_logs</code> returns the count of affected rows or false if something went the other direction.</p> <p>Now I want to display the number of rows that have been deleted. I would imagine something like this:</p> <pre><code>$affected_rows = do_action( 'myplugin_clean_logs' ); echo $affected_rows . ' entries have been deleted.'; </code></pre> <p>But as <code>do_action</code> will not return any value, I have no idea how to get the return value.</p> <p>Should I execute the method directly on a manual run, but use the action on schedule events?</p>
[ { "answer_id": 224425, "author": "Caspar", "author_id": 27191, "author_profile": "https://wordpress.stackexchange.com/users/27191", "pm_score": 4, "selected": false, "text": "<p>The cool thing is a filter is the same as an action, only it returns a value, so just set it up as a filter instead:</p>\n\n<p><code>add_filter( 'myplugin_clean_logs', array( 'MyPlugin_Logs', 'clean_logs' ) );</code></p>\n\n<p>Then something like:</p>\n\n<pre><code>$affected_rows = '';\n$affected_rows = apply_filters( 'myplugin_clean_logs', $affected_rows );\n</code></pre>\n\n<p>should pass <code>$affected_rows</code> to <code>clean_logs()</code> (and whatever other functions you may have hooked to <code>myplugin_clean_logs</code>) and assign the return value back to <code>$affected_rows</code>.</p>\n" }, { "answer_id": 344729, "author": "Goofball", "author_id": 173217, "author_profile": "https://wordpress.stackexchange.com/users/173217", "pm_score": 0, "selected": false, "text": "<p>Never used this function and haven't tested this, but might it work? <a href=\"https://developer.wordpress.org/reference/functions/do_action_ref_array/\" rel=\"nofollow noreferrer\">do_action_ref_array()</a>.</p>\n\n<pre><code>function myplugin_clean_logs_fn() {\n $args = array(\n 'param1' =&gt; 'val1',\n 'param2' =&gt; 'val2',\n 'affected_rows' =&gt; 0,\n );\n do_action_ref_array( 'myplugin_clean_logs', &amp;$args );\n return $args['affected_rows'];\n}\n\n// CALL IT\n$affected_rows = my_plugin_clean_logs();\necho $affected_rows .' entr'. ($args['affected_rows']*1===1?'y':'ies') .' deleted.';\n\n// SCHEDULE IT\nadd_action('myplugin_clean_logs_call_fn', 'myplugin_clean_logs_fn');\nwp_schedule_event( current_time( 'timestamp' ), 'daily', 'myplugin_clean_logs_call_fn' );\n\n// A SAMPLE FILTER\nadd_action('myplugin_clean_logs', function($args) {\n // Cleaning process\n // For each log affected, increment $args['affected_rows'] accordingly\n}, 10, 3);\n</code></pre>\n\n<p>If that doesn't work, why not just filter the thing like Caspar suggested? I mean, that is the purpose of a filter, and in this case the number of affected rows is the thing being filtered. (I miss the old MortCore. Anyone remember how it handled return values, pass-by-reference, and arguments with just a single three parameter function?)</p>\n" }, { "answer_id": 371383, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 1, "selected": false, "text": "<p>This is a very old question but to answer the original question &quot;How to do_action and get a return value?&quot; for anyone looking you can do this using output buffering.</p>\n<pre><code>ob_start();\n do_action( 'myplugin_clean_logs' );\n$action_data = ob_get_clean();\n</code></pre>\n<p>This way you can store the do_action content in a variable.</p>\n" } ]
2016/04/21
[ "https://wordpress.stackexchange.com/questions/224416", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65557/" ]
So there is the following scenario. I add an action to clean logs from the database: ``` add_action( 'myplugin_clean_logs', array( 'MyPlugin_Logs', 'clean_logs' ) ); ``` Now I want to run this action periodically: ``` wp_schedule_event( current_time( 'timestamp' ), 'daily', 'myplugin_clean_logs' ); ``` and execute it manually: ``` do_action( 'myplugin_clean_logs' ); ``` The method `MyPlugin_Logs::clean_logs` returns the count of affected rows or false if something went the other direction. Now I want to display the number of rows that have been deleted. I would imagine something like this: ``` $affected_rows = do_action( 'myplugin_clean_logs' ); echo $affected_rows . ' entries have been deleted.'; ``` But as `do_action` will not return any value, I have no idea how to get the return value. Should I execute the method directly on a manual run, but use the action on schedule events?
The cool thing is a filter is the same as an action, only it returns a value, so just set it up as a filter instead: `add_filter( 'myplugin_clean_logs', array( 'MyPlugin_Logs', 'clean_logs' ) );` Then something like: ``` $affected_rows = ''; $affected_rows = apply_filters( 'myplugin_clean_logs', $affected_rows ); ``` should pass `$affected_rows` to `clean_logs()` (and whatever other functions you may have hooked to `myplugin_clean_logs`) and assign the return value back to `$affected_rows`.
224,467
<p>This is my first go at making my own shortcode.</p> <p><strong>What I am trying to do</strong></p> <p>I have 11 different outputs for star ratings I want to be able to use in posts. I want to wrap it all into one shortcode, and be able to call the specific rating I want. I imagine something like this:</p> <p>[star_rating grade="3"]</p> <p>That would produce 3 out of five stars.</p> <p><strong>What I know</strong></p> <p>I have figured out how to accomplish this using a separate function and shortcode for each grade, but it seems very redundant.</p> <p><strong>What I have</strong></p> <p>This is what I have managed to get so far:</p> <pre><code>function star_rating_5_func( $atts ) { $a = shortcode_atts( array( '5' =&gt; '&lt;i class="fa fa-star"&gt;&lt;/i&gt;&lt;i class="fa fa-star"&gt;&lt;/i&gt;&lt;i class="fa fa-star"&gt;&lt;/i&gt;&lt;i class="fa fa-star"&gt;&lt;/i&gt;&lt;i class="fa fa-star"&gt;&lt;/i&gt;' ), $atts ); return "{$a['5']}"; } add_shortcode( 'star_rating_5', 'star_rating_5_func' ); function star_rating_4_5_func( $atts ) { $a = shortcode_atts( array( '4_5' =&gt; '&lt;i class="fa fa-star"&gt;&lt;/i&gt;&lt;i class="fa fa-star"&gt;&lt;/i&gt;&lt;i class="fa fa-star"&gt;&lt;/i&gt;&lt;i class="fa fa-star"&gt;&lt;/i&gt;&lt;i class="fa fa-star-half-o"&gt;&lt;/i&gt;' ), $atts ); return "{$a['4_5']}"; } add_shortcode( 'star_rating_4_5', 'star_rating_4_5_func' ); </code></pre> <p>This produces a five star rating for [star_rating_5] and a 4.5 star rating for [star_rating_4_5].</p> <p>I'm not very fluent in php, so its a lot of copy and paste at this point. I know you can define variables, and it seems I should be able to simply call a specific one to get the output I want. </p> <p>Is this possible?</p> <p>[star_rating grade="3"] -EXAMPLE</p>
[ { "answer_id": 224425, "author": "Caspar", "author_id": 27191, "author_profile": "https://wordpress.stackexchange.com/users/27191", "pm_score": 4, "selected": false, "text": "<p>The cool thing is a filter is the same as an action, only it returns a value, so just set it up as a filter instead:</p>\n\n<p><code>add_filter( 'myplugin_clean_logs', array( 'MyPlugin_Logs', 'clean_logs' ) );</code></p>\n\n<p>Then something like:</p>\n\n<pre><code>$affected_rows = '';\n$affected_rows = apply_filters( 'myplugin_clean_logs', $affected_rows );\n</code></pre>\n\n<p>should pass <code>$affected_rows</code> to <code>clean_logs()</code> (and whatever other functions you may have hooked to <code>myplugin_clean_logs</code>) and assign the return value back to <code>$affected_rows</code>.</p>\n" }, { "answer_id": 344729, "author": "Goofball", "author_id": 173217, "author_profile": "https://wordpress.stackexchange.com/users/173217", "pm_score": 0, "selected": false, "text": "<p>Never used this function and haven't tested this, but might it work? <a href=\"https://developer.wordpress.org/reference/functions/do_action_ref_array/\" rel=\"nofollow noreferrer\">do_action_ref_array()</a>.</p>\n\n<pre><code>function myplugin_clean_logs_fn() {\n $args = array(\n 'param1' =&gt; 'val1',\n 'param2' =&gt; 'val2',\n 'affected_rows' =&gt; 0,\n );\n do_action_ref_array( 'myplugin_clean_logs', &amp;$args );\n return $args['affected_rows'];\n}\n\n// CALL IT\n$affected_rows = my_plugin_clean_logs();\necho $affected_rows .' entr'. ($args['affected_rows']*1===1?'y':'ies') .' deleted.';\n\n// SCHEDULE IT\nadd_action('myplugin_clean_logs_call_fn', 'myplugin_clean_logs_fn');\nwp_schedule_event( current_time( 'timestamp' ), 'daily', 'myplugin_clean_logs_call_fn' );\n\n// A SAMPLE FILTER\nadd_action('myplugin_clean_logs', function($args) {\n // Cleaning process\n // For each log affected, increment $args['affected_rows'] accordingly\n}, 10, 3);\n</code></pre>\n\n<p>If that doesn't work, why not just filter the thing like Caspar suggested? I mean, that is the purpose of a filter, and in this case the number of affected rows is the thing being filtered. (I miss the old MortCore. Anyone remember how it handled return values, pass-by-reference, and arguments with just a single three parameter function?)</p>\n" }, { "answer_id": 371383, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 1, "selected": false, "text": "<p>This is a very old question but to answer the original question &quot;How to do_action and get a return value?&quot; for anyone looking you can do this using output buffering.</p>\n<pre><code>ob_start();\n do_action( 'myplugin_clean_logs' );\n$action_data = ob_get_clean();\n</code></pre>\n<p>This way you can store the do_action content in a variable.</p>\n" } ]
2016/04/22
[ "https://wordpress.stackexchange.com/questions/224467", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90803/" ]
This is my first go at making my own shortcode. **What I am trying to do** I have 11 different outputs for star ratings I want to be able to use in posts. I want to wrap it all into one shortcode, and be able to call the specific rating I want. I imagine something like this: [star\_rating grade="3"] That would produce 3 out of five stars. **What I know** I have figured out how to accomplish this using a separate function and shortcode for each grade, but it seems very redundant. **What I have** This is what I have managed to get so far: ``` function star_rating_5_func( $atts ) { $a = shortcode_atts( array( '5' => '<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i>' ), $atts ); return "{$a['5']}"; } add_shortcode( 'star_rating_5', 'star_rating_5_func' ); function star_rating_4_5_func( $atts ) { $a = shortcode_atts( array( '4_5' => '<i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star"></i><i class="fa fa-star-half-o"></i>' ), $atts ); return "{$a['4_5']}"; } add_shortcode( 'star_rating_4_5', 'star_rating_4_5_func' ); ``` This produces a five star rating for [star\_rating\_5] and a 4.5 star rating for [star\_rating\_4\_5]. I'm not very fluent in php, so its a lot of copy and paste at this point. I know you can define variables, and it seems I should be able to simply call a specific one to get the output I want. Is this possible? [star\_rating grade="3"] -EXAMPLE
The cool thing is a filter is the same as an action, only it returns a value, so just set it up as a filter instead: `add_filter( 'myplugin_clean_logs', array( 'MyPlugin_Logs', 'clean_logs' ) );` Then something like: ``` $affected_rows = ''; $affected_rows = apply_filters( 'myplugin_clean_logs', $affected_rows ); ``` should pass `$affected_rows` to `clean_logs()` (and whatever other functions you may have hooked to `myplugin_clean_logs`) and assign the return value back to `$affected_rows`.
224,480
<p>I am working on a site where the page titles are generated dynamically from external data sources. So obviously, Yoast SEO/WordPress SEO doesn´t know anything about the correct title, description, image etc. in the head when it outputs OpenGraph tags and more.</p> <p>That should be no problem so far, as WordPress SEO supports filters to hook into the output. You can find them in <a href="https://yoast.com/wordpress/plugins/seo/api/" rel="nofollow">this list</a>.</p> <p>Filters must go into the <code>functions.php</code>, I need to pass my generated data to it and then the hooks will do their magic. As I can´t use variables in <code>add_filter()</code> I need some way around.</p> <p>I am already using <a href="https://wordpress.stackexchange.com/questions/69365/how-to-pass-code-from-header-php-to-footer-php">this technique described by toscho</a> to save data in static variables, so I can access them from around the whole WordPress. (This works fine for everything, except my filters.)</p> <p>So my page template is calling</p> <pre><code>$saved = title_storage($event_title); </code></pre> <p>to save the dynamically generated page title into a static variable for later use.</p> <p>In my <code>functions.php</code> I got the following:</p> <pre><code>function seo_change_title( $string ) { $string = title_storage(); return $string; } add_filter( 'wpseo_title', 'seo_change_title', 10, 1 ); </code></pre> <p>Obviously this doesn´t work. The <code>title</code> is stripped from the OpenGraph tags but that´s everything that changes. Although that probably means, my variable is empty.</p> <p><strong>Trying to get my head around anonymous functions and searching WPSE for solutions, but I thought it could be this easy. Am I getting something wrong here?</strong></p>
[ { "answer_id": 224481, "author": "Z. Zlatev", "author_id": 4192, "author_profile": "https://wordpress.stackexchange.com/users/4192", "pm_score": 2, "selected": false, "text": "<p>Most obvious reason could be the fact <code>wpseo_title</code> filter is firing before you have saved your title. Try moving <code>title_storage()</code> call on a earlier stage like. The <code>wp</code> action should be a good candidate.</p>\n" }, { "answer_id": 224764, "author": "flomei", "author_id": 65455, "author_profile": "https://wordpress.stackexchange.com/users/65455", "pm_score": 0, "selected": false, "text": "<p>Just as Zlatev recommended, I tried to get my data earlier and hook into the Yoast SEO plugin earlier.</p>\n\n<p>This worked fine for me. Had to write three new functions to get the desired data from my external data source, but now I have no more problems with setting title, open graph image and more.</p>\n\n<p><strong>Lesson learned: Write (wrapper) functions to have your data ready, when you need it.</strong></p>\n" } ]
2016/04/22
[ "https://wordpress.stackexchange.com/questions/224480", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65455/" ]
I am working on a site where the page titles are generated dynamically from external data sources. So obviously, Yoast SEO/WordPress SEO doesn´t know anything about the correct title, description, image etc. in the head when it outputs OpenGraph tags and more. That should be no problem so far, as WordPress SEO supports filters to hook into the output. You can find them in [this list](https://yoast.com/wordpress/plugins/seo/api/). Filters must go into the `functions.php`, I need to pass my generated data to it and then the hooks will do their magic. As I can´t use variables in `add_filter()` I need some way around. I am already using [this technique described by toscho](https://wordpress.stackexchange.com/questions/69365/how-to-pass-code-from-header-php-to-footer-php) to save data in static variables, so I can access them from around the whole WordPress. (This works fine for everything, except my filters.) So my page template is calling ``` $saved = title_storage($event_title); ``` to save the dynamically generated page title into a static variable for later use. In my `functions.php` I got the following: ``` function seo_change_title( $string ) { $string = title_storage(); return $string; } add_filter( 'wpseo_title', 'seo_change_title', 10, 1 ); ``` Obviously this doesn´t work. The `title` is stripped from the OpenGraph tags but that´s everything that changes. Although that probably means, my variable is empty. **Trying to get my head around anonymous functions and searching WPSE for solutions, but I thought it could be this easy. Am I getting something wrong here?**
Most obvious reason could be the fact `wpseo_title` filter is firing before you have saved your title. Try moving `title_storage()` call on a earlier stage like. The `wp` action should be a good candidate.
224,485
<p>So there is the following case.</p> <p>I need to display a name inside of <code>admin_notices</code>.</p> <pre><code>class MyPlugin_Admin { public static function render_admin_notice() { echo $name . ' has been upgraded.'; } } add_action( 'admin_notices', array( 'MyPlugin_Admin', 'render_admin_notice' ) ); </code></pre> <p>How to populate <code>$name</code>?</p> <p>I thougth of following solutions:</p> <p>No. 1:</p> <pre><code>class MyPlugin_Admin { public static $name; public static function render_admin_notice() { echo self::$name . ' has been upgraded.'; } } MyPlugin_Admin::$name = 'John Doe'; add_action( 'admin_notices', array( 'MyPlugin_Admin', 'render_admin_notice' ) ); </code></pre> <p>No. 2:</p> <pre><code>$name = 'John Doe'; add_action('admin_notices', function() use ($name){ echo $name . ' has been upgraded.'; }); </code></pre> <p>I don't like both somehow, since No. 1 requires <code>$name</code> to be populate <code>class</code> wide and therefor might lead to confusion and No. 2 requires at least PHP 5.3.</p>
[ { "answer_id": 224501, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 5, "selected": true, "text": "<p>I think a better implementation would be a \"message\" class e.g.:</p>\n\n<pre><code>class WPSE_224485_Message {\n private $_message;\n\n function __construct( $message ) {\n $this-&gt;_message = $message;\n\n add_action( 'admin_notices', array( $this, 'render' ) );\n }\n\n function render() {\n printf( '&lt;div class=\"updated\"&gt;%s&lt;/div&gt;', $this-&gt;_message );\n }\n}\n</code></pre>\n\n<p>This allows you to instantiate the message at any time prior to rendering:</p>\n\n<pre><code>if ( $done ) {\n new WPSE_224485_Message( \"$name has been upgraded.\" );\n}\n</code></pre>\n" }, { "answer_id": 324396, "author": "RavanH", "author_id": 15583, "author_profile": "https://wordpress.stackexchange.com/users/15583", "pm_score": 0, "selected": false, "text": "<p>Can be done much more straight forward:</p>\n\n<pre><code>$message = $name . ' has been upgraded.';\n\nadd_settings_error( 'my_admin_notice', 'my_admin_notice', $message, 'updated' );\n</code></pre>\n\n<p>Read more on <a href=\"https://developer.wordpress.org/reference/functions/add_settings_error/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_settings_error/</a></p>\n" } ]
2016/04/22
[ "https://wordpress.stackexchange.com/questions/224485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65557/" ]
So there is the following case. I need to display a name inside of `admin_notices`. ``` class MyPlugin_Admin { public static function render_admin_notice() { echo $name . ' has been upgraded.'; } } add_action( 'admin_notices', array( 'MyPlugin_Admin', 'render_admin_notice' ) ); ``` How to populate `$name`? I thougth of following solutions: No. 1: ``` class MyPlugin_Admin { public static $name; public static function render_admin_notice() { echo self::$name . ' has been upgraded.'; } } MyPlugin_Admin::$name = 'John Doe'; add_action( 'admin_notices', array( 'MyPlugin_Admin', 'render_admin_notice' ) ); ``` No. 2: ``` $name = 'John Doe'; add_action('admin_notices', function() use ($name){ echo $name . ' has been upgraded.'; }); ``` I don't like both somehow, since No. 1 requires `$name` to be populate `class` wide and therefor might lead to confusion and No. 2 requires at least PHP 5.3.
I think a better implementation would be a "message" class e.g.: ``` class WPSE_224485_Message { private $_message; function __construct( $message ) { $this->_message = $message; add_action( 'admin_notices', array( $this, 'render' ) ); } function render() { printf( '<div class="updated">%s</div>', $this->_message ); } } ``` This allows you to instantiate the message at any time prior to rendering: ``` if ( $done ) { new WPSE_224485_Message( "$name has been upgraded." ); } ```
224,487
<p>I've created a custom post type and would like to send those posts to FB Instant Articles and Apple News via a RSS feed. I've created a custom RSS feed and need to know what's the best way to make that feed password-protected. The CPT is called limitedrun. The feed URL is domain.com/?feed=ltdrun and the RSS template is called rss-ltdrun.php</p> <p>I know there are plugins that do this but it's not what I'm looking for. They password protect the entire site in order to make the RSS feed password-protected. I need the opposite: RSS password-protected and the website open.</p> <p>Thanks,</p>
[ { "answer_id": 224501, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 5, "selected": true, "text": "<p>I think a better implementation would be a \"message\" class e.g.:</p>\n\n<pre><code>class WPSE_224485_Message {\n private $_message;\n\n function __construct( $message ) {\n $this-&gt;_message = $message;\n\n add_action( 'admin_notices', array( $this, 'render' ) );\n }\n\n function render() {\n printf( '&lt;div class=\"updated\"&gt;%s&lt;/div&gt;', $this-&gt;_message );\n }\n}\n</code></pre>\n\n<p>This allows you to instantiate the message at any time prior to rendering:</p>\n\n<pre><code>if ( $done ) {\n new WPSE_224485_Message( \"$name has been upgraded.\" );\n}\n</code></pre>\n" }, { "answer_id": 324396, "author": "RavanH", "author_id": 15583, "author_profile": "https://wordpress.stackexchange.com/users/15583", "pm_score": 0, "selected": false, "text": "<p>Can be done much more straight forward:</p>\n\n<pre><code>$message = $name . ' has been upgraded.';\n\nadd_settings_error( 'my_admin_notice', 'my_admin_notice', $message, 'updated' );\n</code></pre>\n\n<p>Read more on <a href=\"https://developer.wordpress.org/reference/functions/add_settings_error/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_settings_error/</a></p>\n" } ]
2016/04/22
[ "https://wordpress.stackexchange.com/questions/224487", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8049/" ]
I've created a custom post type and would like to send those posts to FB Instant Articles and Apple News via a RSS feed. I've created a custom RSS feed and need to know what's the best way to make that feed password-protected. The CPT is called limitedrun. The feed URL is domain.com/?feed=ltdrun and the RSS template is called rss-ltdrun.php I know there are plugins that do this but it's not what I'm looking for. They password protect the entire site in order to make the RSS feed password-protected. I need the opposite: RSS password-protected and the website open. Thanks,
I think a better implementation would be a "message" class e.g.: ``` class WPSE_224485_Message { private $_message; function __construct( $message ) { $this->_message = $message; add_action( 'admin_notices', array( $this, 'render' ) ); } function render() { printf( '<div class="updated">%s</div>', $this->_message ); } } ``` This allows you to instantiate the message at any time prior to rendering: ``` if ( $done ) { new WPSE_224485_Message( "$name has been upgraded." ); } ```
224,528
<p>I've been using a CPT named "session" that has some date fields. Those date fields are stored via the CMB2 plugin with something like this :</p> <pre><code>$cmb-&gt;add_field( array( 'name' =&gt; __('Begin :', 'cmb2'), 'id' =&gt; $prefix . 'session_datebegin', 'desc' =&gt; __( 'Beginning date of the session', 'cmb2' ), 'type' =&gt; 'text_date', 'date_format' =&gt; 'd-m-Y' ) ); </code></pre> <p>Now I want to display the sessions, ordered by the "closest" date. Here are the args used in my WP query :</p> <pre><code>$args = array( 'post_type' =&gt; 'session', 'posts_per_page' =&gt; -1, 'meta_key' =&gt; 'session_datebegin', 'orderby' =&gt; 'session_datebegin', 'order' =&gt; 'ASC' ); </code></pre> <p>Let's say I have 3 dates : 22-04-2016, 20-04-2016 and 05-05-2016. The previous query gives : 05-05-2016, 20-04-2016, 22-04-2016. As you guessed, using "DESC" instead of "ASC" returned : 22-04-2016, 20-04-2016, 05-05-2016.</p> <p>The date settings for my WP install are custom ones, under this form : d-m-Y.</p> <p>I just can't figure out where the problem takes place : for "may", even there is a confusion somewhere with the US date format, 05-05-2016 will always be equal to 05-05-2016, won't it ?!</p> <p>How can I make a proper sort with this date format ? Thanks</p>
[ { "answer_id": 224529, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>In a nutshell this is a poor format to store date.</p>\n\n<p>You get results you get because 05 &lt; 20 &lt; 22 in that example. You are merely comparing strings and in <em>these</em> date strings day of the month is leading.</p>\n\n<p>You wouldn't be able to easily cast it to MySQL DATE either since that one got YYYY-MM-DD format.</p>\n\n<p>If you need sort you should store your dates in string–sortable format like DATE or store timestamps, which can be sorted as numbers (not human readable though).</p>\n" }, { "answer_id": 224580, "author": "Fafanellu", "author_id": 92582, "author_profile": "https://wordpress.stackexchange.com/users/92582", "pm_score": 1, "selected": false, "text": "<p>For those who experienced the same problem, I finally found a way to do the sort. First I created an extra CMB like this :</p>\n\n<pre><code>$cmb-&gt;add_field( array(\n 'id' =&gt; $prefix . 'session_gooddatebegin',\n 'type' =&gt; 'hidden',\n ) );\n</code></pre>\n\n<p>Then I created an action using <code>save_post</code>. If the CPT \"session\" is being updated, thanks to <code>$update</code>, I assume that the user selected a date in the CMB <code>session_datebegin</code>. Hence, we now are able to update the hidden date field, putting it to the correct form :</p>\n\n<pre><code>add_action( 'save_post', 'good_dates', 99, 3);\n\nfunction good_dates( $post_id, $post, $update ) {\n\n if (get_post_type($post_id)!='session') {\n return;\n }\n\n //if the post is being updated\n if ($update==true) {\n\n //begin date \n $datebegin = get_post_meta( $post_id, 'session_datebegin', true );\n\n //put to the expected form with date() and strtotime() \n $datebegingood = date(\"mdY\", strtotime($datebegin));\n\n //update the hidden variable\n update_post_meta($post_id, 'session_gooddatedeb', $datebegingood );\n }\n\n}\n</code></pre>\n\n<p>Finally, the sort can be performed in the archive page using the same args as before :</p>\n\n<pre><code>$args = array( \n 'post_type' =&gt; 'session', \n 'posts_per_page' =&gt; -1,\n 'meta_key' =&gt; 'session_datebegin', \n 'orderby' =&gt; 'session_datebegin', \n 'order' =&gt; 'ASC' \n );\n</code></pre>\n" } ]
2016/04/22
[ "https://wordpress.stackexchange.com/questions/224528", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92582/" ]
I've been using a CPT named "session" that has some date fields. Those date fields are stored via the CMB2 plugin with something like this : ``` $cmb->add_field( array( 'name' => __('Begin :', 'cmb2'), 'id' => $prefix . 'session_datebegin', 'desc' => __( 'Beginning date of the session', 'cmb2' ), 'type' => 'text_date', 'date_format' => 'd-m-Y' ) ); ``` Now I want to display the sessions, ordered by the "closest" date. Here are the args used in my WP query : ``` $args = array( 'post_type' => 'session', 'posts_per_page' => -1, 'meta_key' => 'session_datebegin', 'orderby' => 'session_datebegin', 'order' => 'ASC' ); ``` Let's say I have 3 dates : 22-04-2016, 20-04-2016 and 05-05-2016. The previous query gives : 05-05-2016, 20-04-2016, 22-04-2016. As you guessed, using "DESC" instead of "ASC" returned : 22-04-2016, 20-04-2016, 05-05-2016. The date settings for my WP install are custom ones, under this form : d-m-Y. I just can't figure out where the problem takes place : for "may", even there is a confusion somewhere with the US date format, 05-05-2016 will always be equal to 05-05-2016, won't it ?! How can I make a proper sort with this date format ? Thanks
For those who experienced the same problem, I finally found a way to do the sort. First I created an extra CMB like this : ``` $cmb->add_field( array( 'id' => $prefix . 'session_gooddatebegin', 'type' => 'hidden', ) ); ``` Then I created an action using `save_post`. If the CPT "session" is being updated, thanks to `$update`, I assume that the user selected a date in the CMB `session_datebegin`. Hence, we now are able to update the hidden date field, putting it to the correct form : ``` add_action( 'save_post', 'good_dates', 99, 3); function good_dates( $post_id, $post, $update ) { if (get_post_type($post_id)!='session') { return; } //if the post is being updated if ($update==true) { //begin date $datebegin = get_post_meta( $post_id, 'session_datebegin', true ); //put to the expected form with date() and strtotime() $datebegingood = date("mdY", strtotime($datebegin)); //update the hidden variable update_post_meta($post_id, 'session_gooddatedeb', $datebegingood ); } } ``` Finally, the sort can be performed in the archive page using the same args as before : ``` $args = array( 'post_type' => 'session', 'posts_per_page' => -1, 'meta_key' => 'session_datebegin', 'orderby' => 'session_datebegin', 'order' => 'ASC' ); ```
224,536
<p>I know that I can use the <code>jpeg_quality</code> filter like this:</p> <p><code>add_filter('jpeg_quality', function($arg){return 75;});</code></p> <p>This will reduce the image quality of the images generated during the upload process such as the <em>thumbnail</em>, <em>medium</em> and <em>large</em> image sizes, however the <strong>original</strong> image is still at the original quailty.</p> <p>Is there a filter or function I can add that will decrease the image quality of the <strong>original</strong> image when it's uploaded?</p>
[ { "answer_id": 224539, "author": "Web-Entwickler", "author_id": 92649, "author_profile": "https://wordpress.stackexchange.com/users/92649", "pm_score": 0, "selected": false, "text": "<p>This answer could help you:\n<a href=\"https://wordpress.stackexchange.com/a/69287/92649\">https://wordpress.stackexchange.com/a/69287/92649</a></p>\n\n<p>You would need to upload your image at a higher resolution than \"large\" to have that effect, though</p>\n" }, { "answer_id": 224545, "author": "MerchantWeb", "author_id": 90412, "author_profile": "https://wordpress.stackexchange.com/users/90412", "pm_score": 1, "selected": false, "text": "<p>There is a plugin called Resize Image After Upload:</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: Resize Image After Upload\nPlugin URI: https://wordpress.org/plugins/resize-image-after-upload/\nDescription: Simple plugin to automatically resize uploaded images to within specified maximum width and height. Also has option to force recompression of JPEGs. Configuration options found under &lt;a href=\"options-general.php?page=resize-after-upload\"&gt;Settings &gt; Resize Image Upload&lt;/a&gt;\nAuthor: iamphilrae\nVersion: 1.7.2\nAuthor URI: http://www.philr.ae/\n\nCopyright (C) 2015 iamphilrae\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License\nas published by the Free Software Foundation; either version 2\nof the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n*/\n\n$PLUGIN_VERSION = '1.7.2';\n$DEBUG_LOGGER = false;\n\n\n// Default plugin values\nif(get_option('jr_resizeupload_version') != $PLUGIN_VERSION) {\n\n add_option('jr_resizeupload_version', $PLUGIN_VERSION, '','yes');\n add_option('jr_resizeupload_width', '1200', '', 'yes');\n add_option('jr_resizeupload_height', '1200', '', 'yes');\n add_option('jr_resizeupload_quality', '90', '', 'yes');\n add_option('jr_resizeupload_resize_yesno', 'yes', '','yes');\n add_option('jr_resizeupload_recompress_yesno', 'no', '','yes');\n add_option('jr_resizeupload_convertbmp_yesno', 'no', '', 'yes');\n add_option('jr_resizeupload_convertpng_yesno', 'no', '', 'yes');\n add_option('jr_resizeupload_convertgif_yesno', 'no', '', 'yes');\n}\n\n\n\n// Hook in the options page\nadd_action('admin_menu', 'jr_uploadresize_options_page');\n\n// Hook the function to the upload handler\nadd_action('wp_handle_upload', 'jr_uploadresize_resize');\n\n\n\n\n/**\n* Add the options page\n*/\nfunction jr_uploadresize_options_page(){\n if(function_exists('add_options_page')){\n add_options_page(\n 'Resize Image After Upload',\n 'Resize Image Upload',\n 'manage_options',\n 'resize-after-upload',\n 'jr_uploadresize_options'\n );\n }\n} // function jr_uploadresize_options_page(){\n\n\n\n/**\n* Define the Options page for the plugin\n*/\nfunction jr_uploadresize_options(){\n\n if(isset($_POST['jr_options_update'])) {\n\n $resizing_enabled = trim(esc_sql($_POST['yesno']));\n $force_jpeg_recompression = trim(esc_sql($_POST['recompress_yesno']));\n\n $max_width = trim(esc_sql($_POST['maxwidth']));\n $max_height = trim(esc_sql($_POST['maxheight']));\n $compression_level = trim(esc_sql($_POST['quality']));\n\n $convert_png_to_jpg = trim(esc_sql(isset($_POST['convertpng']) ? $_POST['convertpng'] : 'no'));\n $convert_gif_to_jpg = trim(esc_sql(isset($_POST['convertgif']) ? $_POST['convertgif'] : 'no'));\n $convert_bmp_to_jpg = trim(esc_sql(isset($_POST['convertbmp']) ? $_POST['convertbmp'] : 'no'));\n\n\n // If input is not an integer, use previous setting\n $max_width = ($max_width == '') ? 0 : $max_width;\n $max_width = (ctype_digit(strval($max_width)) == false) ? get_option('jr_resizeupload_width') : $max_width;\n update_option('jr_resizeupload_width',$max_width);\n\n\n $max_height = ($max_height == '') ? 0 : $max_height;\n $max_height = (ctype_digit(strval($max_height)) == false) ? get_option('jr_resizeupload_height') : $max_height;\n update_option('jr_resizeupload_height',$max_height);\n\n\n $compression_level = ($compression_level == '') ? 1 : $compression_level;\n $compression_level = (ctype_digit(strval($compression_level)) == false) ? get_option('jr_resizeupload_quality') : $compression_level;\n\n if($compression_level &lt; 1) {\n $compression_level = 1;\n }\n else if($compression_level &gt; 100) {\n $compression_level = 100;\n }\n\n update_option('jr_resizeupload_quality',$compression_level);\n\n\n\n\n if ($resizing_enabled == 'yes') {\n update_option('jr_resizeupload_resize_yesno','yes'); }\n else {\n update_option('jr_resizeupload_resize_yesno','no'); }\n\n\n if ($force_jpeg_recompression == 'yes') {\n update_option('jr_resizeupload_recompress_yesno','yes'); }\n else {\n update_option('jr_resizeupload_recompress_yesno','no'); }\n\n\n if ($convert_png_to_jpg == 'yes') {\n update_option('jr_resizeupload_convertpng_yesno','yes'); }\n else {\n update_option('jr_resizeupload_convertpng_yesno','no'); }\n\n if ($convert_gif_to_jpg == 'yes') {\n update_option('jr_resizeupload_convertgif_yesno','yes'); }\n else {\n update_option('jr_resizeupload_convertgif_yesno','no'); }\n\n if ($convert_bmp_to_jpg == 'yes') {\n update_option('jr_resizeupload_convertbmp_yesno','yes'); }\n else {\n update_option('jr_resizeupload_convertbmp_yesno','no'); }\n\n\n\n echo('&lt;div id=\"message\" class=\"updated fade\"&gt;&lt;p&gt;&lt;strong&gt;Options have been updated.&lt;/strong&gt;&lt;/p&gt;&lt;/div&gt;');\n } // if\n\n\n\n // get options and show settings form\n $resizing_enabled = get_option('jr_resizeupload_resize_yesno');\n $force_jpeg_recompression = get_option('jr_resizeupload_recompress_yesno');\n $compression_level = intval(get_option('jr_resizeupload_quality'));\n\n $max_width = get_option('jr_resizeupload_width');\n $max_height = get_option('jr_resizeupload_height');\n\n $convert_png_to_jpg = get_option('jr_resizeupload_convertpng_yesno');\n $convert_gif_to_jpg = get_option('jr_resizeupload_convertgif_yesno');\n $convert_bmp_to_jpg = get_option('jr_resizeupload_convertbmp_yesno');\n?&gt;\n&lt;style type=\"text/css\"&gt;\n.resizeimage-button {\n color: #FFF;\n background: none repeat scroll 0% 0% #FC9A24;\n border-radius: 3px;\n display: inline-block;\n border-bottom: 4px solid #EC8A14;\n margin-right:5px;\n line-height:1.05em;\n text-align: center;\n text-decoration: none;\n padding: 9px 20px 8px;\n font-size: 15px;\n font-weight: bold;\n text-shadow: 0 -1px 1px rgba(0,0,0,0.2);\n}\n\n.resizeimage-button:active,\n.resizeimage-button:hover,\n.resizeimage-button:focus {\n background-color: #EC8A14;\n color: #FFF;\n}\n\n.media-upload-form div.error, .wrap div.error, .wrap div.updated {\n margin: 25px 0px 25px;\n}\n\n&lt;/style&gt;\n\n&lt;div class=\"wrap\"&gt;\n &lt;form method=\"post\" accept-charset=\"utf-8\"&gt;\n\n &lt;h2&gt;&lt;img src=\"&lt;?php echo plugins_url('icon-128x128.png', __FILE__ ); ?&gt;\" style=\"float:right; border:1px solid #ddd;margin:0 0 15px 15px;width:100px; height:100px;\" /&gt;Resize Image After Upload&lt;/h2&gt;\n\n &lt;div style=\"max-width:700px\"&gt;\n &lt;p&gt;This plugin automatically resizes uploaded images (JPEG, GIF, and PNG) to within a given maximum width and/or height to reduce server space usage. This may be necessary due to the fact that images from digital cameras and smartphones can now be over 10MB each due to higher megapixel counts.&lt;/p&gt;\n\n &lt;p&gt;In addition, the plugin can force re-compression of uploaded JPEG images, regardless of whether they are resized or not; and convert uploaded GIF and PNG images into JPEG format.&lt;/p&gt;\n\n &lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; the resizing/recompression process will discard the original uploaded file including EXIF data.&lt;/p&gt;\n\n &lt;p&gt;This plugin is not intended to replace the WordPress &lt;em&gt;add_image_size()&lt;/em&gt; function, but rather complement it. Use this plugin to ensure that no excessively large images are stored on your server, then use &lt;em&gt;add_image_size()&lt;/em&gt; to create versions of the images suitable for positioning in your website theme.&lt;/p&gt;\n\n &lt;p&gt;This plugin uses standard PHP image resizing functions and will require a high amount of memory (RAM) to be allocated to PHP in your php.ini file (e.g 512MB).&lt;/p&gt;\n\n &lt;h4 style=\"font-size: 15px;font-weight: bold;margin: 2em 0 0;\"&gt;Like the plugin?&lt;/h4&gt;\n\n &lt;p&gt;This plugin was written and is maintained for free (as in free beer) by me, &lt;a href=\"http://philr.ae\" target=\"_blank\"&gt;Phil Rae&lt;/a&gt;. If you find it useful please consider donating some small change or bitcoins to my beer fund because beer is very seldom free. Thanks!&lt;/p&gt;\n\n &lt;p style=\"padding-bottom:2em;\" class=\"resizeimage-button-wrapper\"&gt;\n\n &lt;a class=\"resizeimage-button\" href=\"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amp;hosted_button_id=3W4M254AA3KZG\" target=\"_blank\"&gt;Donate cash&lt;/a&gt;\n\n &lt;a class=\"resizeimage-button coinbase-button\" data-code=\"9584265cb76df0b1e99979163de143f5\" data-button-style=\"custom_small\" target=\"_blank\" href=\"https://coinbase.com/checkouts/9584265cb76df0b1e99979163de143f5\"&gt;Donate bitcoins&lt;/a&gt;\n\n &lt;/p&gt;\n &lt;/div&gt;\n\n &lt;hr style=\"margin-top:20px; margin-bottom:0;\"&gt;\n &lt;hr style=\"margin-top:1px; margin-bottom:40px;\"&gt;\n\n &lt;h3&gt;Re-sizing options&lt;/h3&gt;\n &lt;table class=\"form-table\"&gt;\n &lt;tr&gt;\n &lt;th scope=\"row\"&gt;Enable re-sizing&lt;/th&gt;\n &lt;td valign=\"top\"&gt;\n &lt;select name=\"yesno\" id=\"yesno\"&gt;\n &lt;option value=\"no\" label=\"no\" &lt;?php echo ($resizing_enabled == 'no') ? 'selected=\"selected\"' : ''; ?&gt;&gt;NO - do not resize images&lt;/option&gt;\n &lt;option value=\"yes\" label=\"yes\" &lt;?php echo ($resizing_enabled == 'yes') ? 'selected=\"selected\"' : ''; ?&gt;&gt;YES - resize large images&lt;/option&gt;\n &lt;/select&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n\n &lt;tr&gt;\n &lt;th scope=\"row\"&gt;Max image dimensions&lt;/th&gt;\n\n &lt;td&gt;\n &lt;fieldset&gt;&lt;legend class=\"screen-reader-text\"&gt;&lt;span&gt;Maximum width and height&lt;/span&gt;&lt;/legend&gt;\n &lt;label for=\"maxwidth\"&gt;Max width&lt;/label&gt;\n &lt;input name=\"maxwidth\" step=\"1\" min=\"0\" id=\"maxwidth\" class=\"small-text\" type=\"number\" value=\"&lt;?php echo $max_width; ?&gt;\"&gt;\n &amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;label for=\"maxheight\"&gt;Max height&lt;/label&gt;\n &lt;input name=\"maxheight\" step=\"1\" min=\"0\" id=\"maxheight\" class=\"small-text\" type=\"number\" value=\"&lt;?php echo $max_height; ?&gt;\"&gt;\n &lt;p class=\"description\"&gt;Set to zero or very high value to prevent resizing in that dimension.\n &lt;br /&gt;Recommended values: &lt;code&gt;1200&lt;/code&gt;&lt;/p&gt;\n &lt;/fieldset&gt;\n &lt;/td&gt;\n\n\n &lt;/tr&gt;\n\n &lt;/table&gt;\n\n &lt;hr style=\"margin-top:20px; margin-bottom:30px;\"&gt;\n\n &lt;h3&gt;Compression options&lt;/h3&gt;\n &lt;p style=\"max-width:700px\"&gt;The following settings will only apply to uploaded JPEG images and images converted to JPEG format.&lt;/p&gt;\n\n &lt;table class=\"form-table\"&gt;\n\n &lt;tr&gt;\n &lt;th scope=\"row\"&gt;JPEG compression level&lt;/th&gt;\n &lt;td valign=\"top\"&gt;\n &lt;select id=\"quality\" name=\"quality\"&gt;\n &lt;?php for($i=1; $i&lt;=100; $i++) : ?&gt;\n &lt;option value=\"&lt;?php echo $i; ?&gt;\" &lt;?php if($compression_level == $i) : ?&gt;selected&lt;?php endif; ?&gt;&gt;&lt;?php echo $i; ?&gt;&lt;/option&gt;\n &lt;?php endfor; ?&gt;\n &lt;/select&gt;\n &lt;p class=\"description\"&gt;&lt;code&gt;1&lt;/code&gt; = low quality (smallest files)\n &lt;br&gt;&lt;code&gt;100&lt;/code&gt; = best quality (largest files)\n &lt;br&gt;Recommended value: &lt;code&gt;90&lt;/code&gt;&lt;/p&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n\n &lt;tr&gt;\n &lt;th scope=\"row\"&gt;Force JPEG re-compression&lt;/th&gt;\n &lt;td&gt;\n &lt;select name=\"recompress_yesno\" id=\"yesno\"&gt;\n &lt;option value=\"no\" label=\"no\" &lt;?php echo ($force_jpeg_recompression == 'no') ? 'selected=\"selected\"' : ''; ?&gt;&gt;NO - only re-compress resized jpeg images&lt;/option&gt;\n &lt;option value=\"yes\" label=\"yes\" &lt;?php echo ($force_jpeg_recompression == 'yes') ? 'selected=\"selected\"' : ''; ?&gt;&gt;YES - re-compress all uploaded jpeg images&lt;/option&gt;\n &lt;/select&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n\n &lt;/table&gt;\n\n &lt;?php /* DEFINED HERE FOR FUTURE RELEASE - does not do anything if uncommented\n &lt;hr style=\"margin-top:20px; margin-bottom:20px;\"&gt;\n\n &lt;h3&gt;Image conversion options&lt;/h3&gt;\n &lt;p style=\"max-width:700px\"&gt;Photos saved as PNG and GIF images can be extremely large in file size due to their compression methods not being suited for photos. Enable these options below to automatically convert GIF and/or PNG images to JPEG.&lt;/p&gt;\n\n &lt;p&gt;When enabled, conversion will happen to all uploaded GIF/PNG images, not just ones that require resizing.&lt;/p&gt;\n\n &lt;table class=\"form-table\"&gt;\n\n &lt;tr&gt;\n &lt;th scope=\"row\"&gt;Convert GIF to JPEG&lt;/th&gt;\n &lt;td&gt;\n &lt;select id=\"convert-gif\" name=\"convertgif\"&gt;\n &lt;option value=\"no\" &lt;?php if($convert_gif_to_jpg == 'no') : ?&gt;selected&lt;?php endif; ?&gt;&gt;NO - just resize uploaded gif images as normal&lt;/option&gt;\n &lt;option value=\"yes\" &lt;?php if($convert_gif_to_jpg == 'yes') : ?&gt;selected&lt;?php endif; ?&gt;&gt;YES - convert all uploaded gif images to jpeg&lt;/option&gt;\n &lt;/select&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n\n &lt;tr&gt;\n &lt;th scope=\"row\"&gt;Convert PNG to JPEG&lt;/th&gt;\n &lt;td&gt;\n &lt;select id=\"convert-png\" name=\"convertpng\"&gt;\n &lt;option value=\"no\" &lt;?php if($convert_png_to_jpg == 'no') : ?&gt;selected&lt;?php endif; ?&gt;&gt;NO - just resize uploaded png images as normal&lt;/option&gt;\n &lt;option value=\"yes\" &lt;?php if($convert_png_to_jpg == 'yes') : ?&gt;selected&lt;?php endif; ?&gt;&gt;YES - convert all uploaded png images to jpeg&lt;/option&gt;\n &lt;/select&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n\n &lt;/table&gt;\n */ ?&gt;\n\n &lt;hr style=\"margin-top:30px;\"&gt;\n\n &lt;p class=\"submit\" style=\"margin-top:10px;border-top:1px solid #eee;padding-top:20px;\"&gt;\n &lt;input type=\"hidden\" id=\"convert-bmp\" name=\"convertbmp\" value=\"no\" /&gt;\n &lt;input type=\"hidden\" name=\"action\" value=\"update\" /&gt;\n &lt;input id=\"submit\" name=\"jr_options_update\" class=\"button button-primary\" type=\"submit\" value=\"Update Options\"&gt;\n &lt;/p&gt;\n &lt;/form&gt;\n\n&lt;/div&gt;\n&lt;?php\n} // function jr_uploadresize_options(){\n\n\n\n\n\n/**\n* This function will apply changes to the uploaded file\n* @param $image_data - contains file, url, type\n*/\nfunction jr_uploadresize_resize($image_data){\n\n\n jr_error_log(\"**-start--resize-image-upload\");\n\n\n $resizing_enabled = get_option('jr_resizeupload_resize_yesno');\n $resizing_enabled = ($resizing_enabled=='yes') ? true : false;\n\n $force_jpeg_recompression = get_option('jr_resizeupload_recompress_yesno');\n $force_jpeg_recompression = ($force_jpeg_recompression=='yes') ? true : false;\n\n $compression_level = get_option('jr_resizeupload_quality');\n\n\n $max_width = get_option('jr_resizeupload_width')==0 ? false : get_option('jr_resizeupload_width');\n\n $max_height = get_option('jr_resizeupload_height')==0 ? false : get_option('jr_resizeupload_height');\n\n\n $convert_png_to_jpg = get_option('jr_resizeupload_convertpng_yesno');\n $convert_png_to_jpg = ($convert_png_to_jpg=='yes') ? true : false;\n\n $convert_gif_to_jpg = get_option('jr_resizeupload_convertgif_yesno');\n $convert_gif_to_jpg = ($convert_gif_to_jpg=='yes') ? true : false;\n\n $convert_bmp_to_jpg = get_option('jr_resizeupload_convertbmp_yesno');\n $convert_bmp_to_jpg = ($convert_bmp_to_jpg=='yes') ? true : false;\n\n\n\n //---------- In with the old v1.6.2, new v1.7 (WP_Image_Editor) ------------\n\n if($resizing_enabled || $force_jpeg_recompression) {\n\n $fatal_error_reported = false;\n $valid_types = array('image/gif','image/png','image/jpeg','image/jpg');\n\n if(empty($image_data['file']) || empty($image_data['type'])) {\n jr_error_log(\"--non-data-in-file-( \".print_r($image_data, true).\" )\"); \n $fatal_error_reported = true;\n }\n else if(!in_array($image_data['type'], $valid_types)) {\n jr_error_log(\"--non-image-type-uploaded-( \".$image_data['type'].\" )\");\n $fatal_error_reported = true;\n }\n\n jr_error_log(\"--filename-( \".$image_data['file'].\" )\");\n $image_editor = wp_get_image_editor($image_data['file']);\n $image_type = $image_data['type'];\n\n\n if($fatal_error_reported || is_wp_error($image_editor)) {\n jr_error_log(\"--wp-error-reported\");\n }\n else {\n\n $to_save = false;\n $resized = false;\n\n\n // Perform resizing if required\n if($resizing_enabled) {\n\n jr_error_log(\"--resizing-enabled\");\n $sizes = $image_editor-&gt;get_size();\n\n if((isset($sizes['width']) &amp;&amp; $sizes['width'] &gt; $max_width)\n || (isset($sizes['height']) &amp;&amp; $sizes['height'] &gt; $max_height)) {\n\n $image_editor-&gt;resize($max_width, $max_height, false);\n $resized = true;\n $to_save = true;\n\n $sizes = $image_editor-&gt;get_size();\n jr_error_log(\"--new-size--\".$sizes['width'].\"x\".$sizes['height']);\n }\n else {\n jr_error_log(\"--no-resizing-needed\");\n }\n }\n else {\n jr_error_log(\"--no-resizing-requested\");\n }\n\n\n // Regardless of resizing, image must be saved if recompressing\n if($force_jpeg_recompression &amp;&amp; ($image_type=='image/jpg' || $image_type=='image/jpeg')) {\n\n $to_save = true;\n jr_error_log(\"--compression-level--q-\".$compression_level);\n }\n elseif(!$resized) {\n jr_error_log(\"--no-forced-recompression\");\n }\n\n\n // Only save image if it has been resized or need recompressing\n if($to_save) {\n\n $image_editor-&gt;set_quality($compression_level);\n $saved_image = $image_editor-&gt;save($image_data['file']);\n jr_error_log(\"--image-saved\");\n }\n else {\n jr_error_log(\"--no-changes-to-save\");\n }\n }\n } // if($resizing_enabled || $force_jpeg_recompression)\n\n else {\n jr_error_log(\"--no-action-required\");\n }\n\n jr_error_log(\"**-end--resize-image-upload\\n\");\n\n\n return $image_data;\n} // function jr_uploadresize_resize($image_data){\n\n\n/**\n* Simple debug logging function. Will only output to the log file\n* if 'debugging' is turned on.\n*/\nfunction jr_error_log($message) {\n global $DEBUG_LOGGER;\n\n if($DEBUG_LOGGER) {\n error_log(print_r($message, true));\n }\n}\n</code></pre>\n" }, { "answer_id": 224557, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p>In general I wouldn't recommend modifying the original uploaded image files, just in case we might need to re-generate intermediate sizes.</p>\n\n<p><em>But let's see if it's possible :-)</em></p>\n\n<p>We can in general let WordPress choose the image editor, that depends on modules like <em>GD</em> or <em>Imagick</em>, through:</p>\n\n<pre><code>$editor = wp_get_image_editor( $file );\n</code></pre>\n\n<p>but this can return an <code>WP_Error</code> object, so we better check it with <code>is_wp_error( $editor )</code> before using it.</p>\n\n<p>It's useful to let the image editor handle things through methods like <code>set_quality()</code> and <code>save()</code>. We can see such an usage example in the <em>Resize Image After Upload</em> plugin, mentioned by @MerchantWeb. This is also used by the core in various ways.</p>\n\n<p>The plugin hooks into the <code>wp_handle_upload</code> filter to modify the original uploaded jpeg image files, as far as I understand it.</p>\n\n<p><strong>A)</strong> We could therefore use something like the following, to modify the quality of the original jpeg image file (to e.g. 90) during uploads:</p>\n\n<pre><code>/**\n * A) Modify the quality of original jpeg images to 90, during uploads\n */\nadd_filter( 'wp_handle_upload', function( $data )\n{\n if( ! isset( $data['file'] ) || ! isset( $data['type'] ) )\n return $data;\n\n // Target jpeg images \n if( in_array( $data['type'], [ 'image/jpg', 'image/jpeg' ] ) )\n {\n // Check for a valid image editor\n $editor = wp_get_image_editor( $data['file'] ); \n if( ! is_wp_error( $editor ) )\n {\n // Set the new image quality\n $result = $editor-&gt;set_quality( 90 );\n\n // Re-save the original image file\n if( ! is_wp_error( $result ) )\n $editor-&gt;save( $data['file'] );\n }\n }\n return $data;\n} );\n</code></pre>\n\n<p>but it looks to me that this will also affect all the intermediate sizes, because this runs <strong>before</strong> they are generated.</p>\n\n<p><strong>B)</strong> If we take a look at the <a href=\"https://github.com/WordPress/WordPress/blob/be6a91bf581296ce67acf242f9e92e940c908003/wp-admin/includes/media.php#L261\" rel=\"noreferrer\"><code>media_handle_upload()</code></a> function, we might consider hooking into the <a href=\"https://github.com/WordPress/WordPress/blob/be6a91bf581296ce67acf242f9e92e940c908003/wp-admin/includes/image.php#L201\" rel=\"noreferrer\"><code>wp_generate_attachment_metadata</code></a> filter instead, to modify the original jpeg image file, <strong>after</strong> the intermediate sizes have been generated.</p>\n\n<p>Here's an example (<em>PHP 5.4+</em>):</p>\n\n<pre><code>/**\n * B) Modify the quality of original jpeg images to 90, during uploads\n */\nadd_filter( 'wp_generate_attachment_metadata', function( $metadata, $attachment_id ) \n{\n $file = get_attached_file( $attachment_id );\n $type = get_post_mime_type( $attachment_id );\n\n // Target jpeg images\n if( in_array( $type, [ 'image/jpg', 'image/jpeg' ] ) )\n {\n // Check for a valid image editor\n $editor = wp_get_image_editor( $file );\n if( ! is_wp_error( $editor ) )\n {\n // Set the new image quality\n $result = $editor-&gt;set_quality( 90 );\n\n // Re-save the original image file\n if( ! is_wp_error( $result ) )\n $editor-&gt;save( $file );\n }\n } \n return $metadata;\n}, 10, 2 );\n</code></pre>\n\n<p>If we needed to restrict this further, we might wrap this into the <code>wp_handle_upload</code> hook as well and check for the relevant <em>action</em> context, like <em>wp_handle_upload</em> or <em>sideload</em>.</p>\n\n<p>We might also need to set the quality very low while testing, just to see if it worked ;-)</p>\n\n<p><strong>Note</strong>: These are only demos, that would need further testing.</p>\n\n<p><strong>Update:</strong> Just did some simple testing with an image of our kitchen wall clock. Here we can see that when the full size image is re-saved, with quality 5, then all the intermediate sizes:</p>\n\n<ul>\n<li>A) are also at low quality. </li>\n<li>B) are not affected.</li>\n</ul>\n\n<p>Here are the combined results:</p>\n\n<p><a href=\"https://i.stack.imgur.com/ncLpD.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ncLpD.jpg\" alt=\"a\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/8zGai.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/8zGai.jpg\" alt=\"b\"></a></p>\n" } ]
2016/04/22
[ "https://wordpress.stackexchange.com/questions/224536", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57849/" ]
I know that I can use the `jpeg_quality` filter like this: `add_filter('jpeg_quality', function($arg){return 75;});` This will reduce the image quality of the images generated during the upload process such as the *thumbnail*, *medium* and *large* image sizes, however the **original** image is still at the original quailty. Is there a filter or function I can add that will decrease the image quality of the **original** image when it's uploaded?
In general I wouldn't recommend modifying the original uploaded image files, just in case we might need to re-generate intermediate sizes. *But let's see if it's possible :-)* We can in general let WordPress choose the image editor, that depends on modules like *GD* or *Imagick*, through: ``` $editor = wp_get_image_editor( $file ); ``` but this can return an `WP_Error` object, so we better check it with `is_wp_error( $editor )` before using it. It's useful to let the image editor handle things through methods like `set_quality()` and `save()`. We can see such an usage example in the *Resize Image After Upload* plugin, mentioned by @MerchantWeb. This is also used by the core in various ways. The plugin hooks into the `wp_handle_upload` filter to modify the original uploaded jpeg image files, as far as I understand it. **A)** We could therefore use something like the following, to modify the quality of the original jpeg image file (to e.g. 90) during uploads: ``` /** * A) Modify the quality of original jpeg images to 90, during uploads */ add_filter( 'wp_handle_upload', function( $data ) { if( ! isset( $data['file'] ) || ! isset( $data['type'] ) ) return $data; // Target jpeg images if( in_array( $data['type'], [ 'image/jpg', 'image/jpeg' ] ) ) { // Check for a valid image editor $editor = wp_get_image_editor( $data['file'] ); if( ! is_wp_error( $editor ) ) { // Set the new image quality $result = $editor->set_quality( 90 ); // Re-save the original image file if( ! is_wp_error( $result ) ) $editor->save( $data['file'] ); } } return $data; } ); ``` but it looks to me that this will also affect all the intermediate sizes, because this runs **before** they are generated. **B)** If we take a look at the [`media_handle_upload()`](https://github.com/WordPress/WordPress/blob/be6a91bf581296ce67acf242f9e92e940c908003/wp-admin/includes/media.php#L261) function, we might consider hooking into the [`wp_generate_attachment_metadata`](https://github.com/WordPress/WordPress/blob/be6a91bf581296ce67acf242f9e92e940c908003/wp-admin/includes/image.php#L201) filter instead, to modify the original jpeg image file, **after** the intermediate sizes have been generated. Here's an example (*PHP 5.4+*): ``` /** * B) Modify the quality of original jpeg images to 90, during uploads */ add_filter( 'wp_generate_attachment_metadata', function( $metadata, $attachment_id ) { $file = get_attached_file( $attachment_id ); $type = get_post_mime_type( $attachment_id ); // Target jpeg images if( in_array( $type, [ 'image/jpg', 'image/jpeg' ] ) ) { // Check for a valid image editor $editor = wp_get_image_editor( $file ); if( ! is_wp_error( $editor ) ) { // Set the new image quality $result = $editor->set_quality( 90 ); // Re-save the original image file if( ! is_wp_error( $result ) ) $editor->save( $file ); } } return $metadata; }, 10, 2 ); ``` If we needed to restrict this further, we might wrap this into the `wp_handle_upload` hook as well and check for the relevant *action* context, like *wp\_handle\_upload* or *sideload*. We might also need to set the quality very low while testing, just to see if it worked ;-) **Note**: These are only demos, that would need further testing. **Update:** Just did some simple testing with an image of our kitchen wall clock. Here we can see that when the full size image is re-saved, with quality 5, then all the intermediate sizes: * A) are also at low quality. * B) are not affected. Here are the combined results: [![a](https://i.stack.imgur.com/ncLpD.jpg)](https://i.stack.imgur.com/ncLpD.jpg) [![b](https://i.stack.imgur.com/8zGai.jpg)](https://i.stack.imgur.com/8zGai.jpg)
224,540
<p>I currently have a dive set up which I would like to display different bits of information when the user is logged in and has a specific role. </p> <p>I have three roles 'administrator' 'adoption-agency' and 'shop-manager' which I would like to display a link to the admin area. Then I have a role named 'customer' which I would like to display a link to an internal page if customer is logged in and the user role matches. I have created an <code>if else</code> statement code but I seem to be getting errors. </p> <p>I was wondering if someone could tell me what I am doing wrong.</p> <pre><code> &lt;?php if ( is_user_logged_in() &amp;&amp; (current_user_can('administrator') || current_user_can('shop-manager') || current_user_can('adoption-agency'))) { echo '&lt;p&gt;&lt;span&gt;Welcome: &lt;/span&gt;' . $current_user-&gt;user_login . '&lt;/p&gt;'; echo '&lt;p&gt;&lt;i class="fa fa-smile-o" &gt;&lt;/i&gt; &lt;a href="'. get_admin_url() .'"&gt;Post&lt;/a&gt;&lt;/p&gt;'; echo '&lt;p&gt;&lt;i class="fa fa-unlock-alt" &gt;&lt;/i&gt; &lt;a href="'. wp_logout_url() .'"&gt;Logout&lt;/a&gt;&lt;/p&gt;'; }else if( is_user_logged_in() &amp;&amp; (current_user_can('customer')){ echo '&lt;a href="' .get_page_link( get_page_by_title( account )-&gt;ID ).'"&gt;My account&lt;/a&gt;'; }else{ //default menu echo wp_login_form(); } ?&gt; </code></pre>
[ { "answer_id": 224554, "author": "Caspar", "author_id": 27191, "author_profile": "https://wordpress.stackexchange.com/users/27191", "pm_score": 1, "selected": false, "text": "<p>Your problem is that <code>current_user_can()</code> takes a <em>capability</em> not a user role. So, to check for an administrator, for example, you might use:</p>\n\n<pre><code>if ( current_user_can( 'manage_options' ) ) { ... }\n</code></pre>\n\n<p>because ordinarily only admins can manage options.</p>\n\n<p>You'd have to tie your custom user roles to capabilities that correspond to their roles, which are defined for each role when you create it with <a href=\"https://codex.wordpress.org/Function_Reference/add_role\" rel=\"nofollow\"><code>add_role()</code></a>. For a complete listing of built-in WP roles and their corresponding capabilities, see <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow\">the codex</a>.</p>\n" }, { "answer_id": 224564, "author": "user5200704", "author_id": 92477, "author_profile": "https://wordpress.stackexchange.com/users/92477", "pm_score": 0, "selected": false, "text": "<p>Jevuska is answer is corrected below detail of code check user role current user and display content conditionally.</p>\n\n<pre><code>if ( is_user_logged_in() ){\n $current_user = wp_get_current_user();\n $roles = $current_user-&gt;roles; \n $level = 0;\n foreach( $roles as $role ){\n if( in_array( array( 'administrator', 'shop-manager', 'adoption-agency'), $role ) ){\n $level = 1;\n break; \n }else if( in_array( array( 'customer'), $role ) ){\n $level = 2;\n break; \n }\n }\n if( $level == 1 ){\n echo '&lt;p&gt;&lt;span&gt;Welcome: &lt;/span&gt;' . $current_user-&gt;user_login . '&lt;/p&gt;';\n echo '&lt;p&gt;&lt;i class=\"fa fa-smile-o\" &gt;&lt;/i&gt;\n &lt;a href=\"'. get_admin_url() .'\"&gt;Post&lt;/a&gt;&lt;/p&gt;';\n echo '&lt;p&gt;&lt;i class=\"fa fa-unlock-alt\" &gt;&lt;/i&gt;\n &lt;a href=\"'. wp_logout_url() .'\"&gt;Logout&lt;/a&gt;&lt;/p&gt;';\n }else if( $level == 2 ){\n echo '&lt;a href=\"' .get_page_link( get_page_by_title( account )-&gt;ID ).'\"&gt;My account&lt;/a&gt;';\n\n }//else {\n // put default leave comment \n //}\n }else{\n echo wp_login_form(); \n}\n</code></pre>\n\n<p>OR </p>\n\n<pre><code>if ( is_user_logged_in() ){\n $current_user = wp_get_current_user();\n $roles = $current_user-&gt;roles; \n if( in_array( 'administrator', $role ) || in_array( 'shop-manager', $role ) || in_array( 'adoption-agency', $role )){\n echo '&lt;p&gt;&lt;span&gt;Welcome: &lt;/span&gt;' . $current_user-&gt;user_login . '&lt;/p&gt;';\n echo '&lt;p&gt;&lt;i class=\"fa fa-smile-o\" &gt;&lt;/i&gt;\n &lt;a href=\"'. get_admin_url() .'\"&gt;Post&lt;/a&gt;&lt;/p&gt;';\n echo '&lt;p&gt;&lt;i class=\"fa fa-unlock-alt\" &gt;&lt;/i&gt;\n &lt;a href=\"'. wp_logout_url() .'\"&gt;Logout&lt;/a&gt;&lt;/p&gt;';\n }else if( in_array( 'customer', $role ) ){\n echo '&lt;a href=\"' .get_page_link( get_page_by_title( account )-&gt;ID ).'\"&gt;My account&lt;/a&gt;';\n\n }//else {\n // put default leave comment \n //}\n }else{\n echo wp_login_form(); \n}\n</code></pre>\n" } ]
2016/04/22
[ "https://wordpress.stackexchange.com/questions/224540", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67512/" ]
I currently have a dive set up which I would like to display different bits of information when the user is logged in and has a specific role. I have three roles 'administrator' 'adoption-agency' and 'shop-manager' which I would like to display a link to the admin area. Then I have a role named 'customer' which I would like to display a link to an internal page if customer is logged in and the user role matches. I have created an `if else` statement code but I seem to be getting errors. I was wondering if someone could tell me what I am doing wrong. ``` <?php if ( is_user_logged_in() && (current_user_can('administrator') || current_user_can('shop-manager') || current_user_can('adoption-agency'))) { echo '<p><span>Welcome: </span>' . $current_user->user_login . '</p>'; echo '<p><i class="fa fa-smile-o" ></i> <a href="'. get_admin_url() .'">Post</a></p>'; echo '<p><i class="fa fa-unlock-alt" ></i> <a href="'. wp_logout_url() .'">Logout</a></p>'; }else if( is_user_logged_in() && (current_user_can('customer')){ echo '<a href="' .get_page_link( get_page_by_title( account )->ID ).'">My account</a>'; }else{ //default menu echo wp_login_form(); } ?> ```
Your problem is that `current_user_can()` takes a *capability* not a user role. So, to check for an administrator, for example, you might use: ``` if ( current_user_can( 'manage_options' ) ) { ... } ``` because ordinarily only admins can manage options. You'd have to tie your custom user roles to capabilities that correspond to their roles, which are defined for each role when you create it with [`add_role()`](https://codex.wordpress.org/Function_Reference/add_role). For a complete listing of built-in WP roles and their corresponding capabilities, see [the codex](https://codex.wordpress.org/Roles_and_Capabilities).
224,578
<p>I'm running some template files outside of the actual theme and I am displaying some posts on this templates. Everything worked absolutely fine but some days ago (maybe the update to 4.5) the default settings of WordPress started to override my <code>posts_per_page=-1</code> and I have no clue why this is starting. (No new plugins installed)</p> <pre><code>&lt;?php // Include WordPress define('WP_USE_THEMES', false); require('./../wp-blog-header.php'); query_posts('tag=tagname&amp;posts_per_page=-1'); ?&gt; &lt;?php while (have_posts()): the_post(); ?&gt; &lt;section class="in_tab"&gt; &lt;figure class="tab_fig"&gt; &lt;?php the_post_thumbnail('thumbnail'); ?&gt; &lt;/figure&gt; &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt; &lt;a class="insidelink" target="_blank" href="&lt;?php the_permalink(); ?&gt;" &gt;Weiter...&lt;/a&gt; &lt;/section&gt; &lt;?php endwhile; ?&gt; </code></pre>
[ { "answer_id": 224596, "author": "Steve", "author_id": 92874, "author_profile": "https://wordpress.stackexchange.com/users/92874", "pm_score": 1, "selected": true, "text": "<p>I found the problem. Here is the solution in case someone stumbles upon a similar problem.</p>\n\n<p>I had a filter in my functions.php that limited the showed posts on several custom taxonomies and the default value was set in the else statement</p>\n\n<pre><code>// Customizing posts per page on zitate archive \n\nfunction limit_posts_per_archive_page() {\nif ( is_post_type_archive( 'zitate-sprueche' ) || is_tax('zitate-kats') || is_post_type_archive('daten') || is_tax('daten-kats')) {\n $limit = 27;\n}\nelse if (is_post_type_archive( 'videos' ) || is_tax('videos-kats') || is_post_type_archive( 'whitepaper' ) || is_tax('whitepaper-kats')) {\n $limit = 9;\n}\nelse \n $limit = get_option('posts_per_page');\n\nset_query_var('posts_per_archive_page', $limit);\n}\nadd_filter('pre_get_posts', 'limit_posts_per_archive_page');\n</code></pre>\n\n<p>I changed the else to </p>\n\n<pre><code>else {\n// do nothing :)\n}\n</code></pre>\n\n<p>Now it works as usual</p>\n" }, { "answer_id": 333032, "author": "kitchin", "author_id": 34438, "author_profile": "https://wordpress.stackexchange.com/users/34438", "pm_score": 2, "selected": false, "text": "<p>Regarding my comment to Steve's answer, see also <a href=\"https://wordpress.stackexchange.com/questions/8796/override-the-default-number-of-posts-to-show-for-a-single-loop\">Override the default number of posts to show for a single loop?</a> The \"method\" version of Steve's answer would be:</p>\n\n<pre><code>function limit_posts_per_archive_page( $query ) {\n if ( $query-&gt;is_post_type_archive( 'zitate-sprueche' ) || $query-&gt;is_tax('zitate-kats') || $query-&gt;is_post_type_archive('daten') || $query-&gt;is_tax('daten-kats')) {\n $limit = 27;\n } else \n $limit = get_option('posts_per_page');\n }\n $query-&gt;set( 'posts_per_archive_page', $limit );\n}\nadd_action( 'pre_get_posts', 'limit_posts_per_archive_page' );\n</code></pre>\n\n<p>Similar code works for me.</p>\n" } ]
2016/04/23
[ "https://wordpress.stackexchange.com/questions/224578", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92874/" ]
I'm running some template files outside of the actual theme and I am displaying some posts on this templates. Everything worked absolutely fine but some days ago (maybe the update to 4.5) the default settings of WordPress started to override my `posts_per_page=-1` and I have no clue why this is starting. (No new plugins installed) ``` <?php // Include WordPress define('WP_USE_THEMES', false); require('./../wp-blog-header.php'); query_posts('tag=tagname&posts_per_page=-1'); ?> <?php while (have_posts()): the_post(); ?> <section class="in_tab"> <figure class="tab_fig"> <?php the_post_thumbnail('thumbnail'); ?> </figure> <h2><?php the_title(); ?></h2> <a class="insidelink" target="_blank" href="<?php the_permalink(); ?>" >Weiter...</a> </section> <?php endwhile; ?> ```
I found the problem. Here is the solution in case someone stumbles upon a similar problem. I had a filter in my functions.php that limited the showed posts on several custom taxonomies and the default value was set in the else statement ``` // Customizing posts per page on zitate archive function limit_posts_per_archive_page() { if ( is_post_type_archive( 'zitate-sprueche' ) || is_tax('zitate-kats') || is_post_type_archive('daten') || is_tax('daten-kats')) { $limit = 27; } else if (is_post_type_archive( 'videos' ) || is_tax('videos-kats') || is_post_type_archive( 'whitepaper' ) || is_tax('whitepaper-kats')) { $limit = 9; } else $limit = get_option('posts_per_page'); set_query_var('posts_per_archive_page', $limit); } add_filter('pre_get_posts', 'limit_posts_per_archive_page'); ``` I changed the else to ``` else { // do nothing :) } ``` Now it works as usual
224,592
<p>I see the following code a lot in index.php files. I understand that <code>is_front_page()</code> returns true when viewing the Site Front Page (whether displaying the blog posts index or a static page), while <code>is_home()</code> returns true when viewing the Blog Posts Index (whether displayed on the front page or on a static page). I am still somewhat stumped about the use of the following code - </p> <pre><code>&lt;?php if ( have_posts() ) : ?&gt; &lt;?php if ( is_home() &amp;&amp; ! is_front_page() ) : ?&gt; &lt;header&gt; &lt;h1 class="page-title screen-reader-text"&gt;&lt;?php single_post_title(); ?&gt;&lt;/h1&gt; &lt;/header&gt; &lt;?php endif; ?&gt; </code></pre> <p>Any explanation of why this piece of code is so popular is greatly appreciated. </p>
[ { "answer_id": 224594, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>I am not sure about \"popular\", it doesn't seem so to me (but then I don't look at that many themes).</p>\n\n<p>You seem to grasp fine what each conditional does, so this shouldn't be confusing to you. This combines conditions to check that blog index is being displayed <strong>and</strong> it's <strong>not</strong> at the front page.</p>\n\n<p>Ah, the reason for <code>single_post_title()</code> I would guess is that it displays title for <code>$wp_query-&gt;queried object</code> (set up by main query as current context), rather than <code>$post</code> global (set up by iterating loop).</p>\n\n<p>In some circumstances these will be same, but not in such case as condition checks for. The loop will contain <em>posts</em>, but queried object will be <em>page</em> (unless I am mixing things up :).</p>\n" }, { "answer_id": 224598, "author": "shramee", "author_id": 92887, "author_profile": "https://wordpress.stackexchange.com/users/92887", "pm_score": 5, "selected": true, "text": "<p>This will display the title of the <strong>page</strong> when a static page is set to show posts.</p>\n\n<p><strong>E.g.</strong></p>\n\n<p>I show posts on my homepage...\nIt'll do nothing.</p>\n\n<p>If I, say, show posts on page titled <strong>News</strong>...\nIt'll show <strong>News</strong> in H1.</p>\n\n<p>This is used so that the title of the page is shown, whenever posts are shown on a page, but nothing when blog posts are shown on the front page (home page).</p>\n\n<p>We do it because if it's on home page... it will show the title of the first post, making it appear twice (once at the top in H1 and again when posts are looped through).</p>\n" }, { "answer_id": 239838, "author": "Md. Abunaser Khan", "author_id": 103030, "author_profile": "https://wordpress.stackexchange.com/users/103030", "pm_score": 6, "selected": false, "text": "<p>Here is how to do it right:</p>\n\n<pre><code>if ( is_front_page() &amp;&amp; is_home() ) {\n// Default homepage\n\n} elseif ( is_front_page()){\n// Static homepage\n\n} elseif ( is_home()){\n\n// Blog page\n\n} else {\n\n// Everything else\n\n}\n</code></pre>\n\n<p>This is the only (right) way to display or alter content with your homepage and your blog page.</p>\n" } ]
2016/04/23
[ "https://wordpress.stackexchange.com/questions/224592", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81978/" ]
I see the following code a lot in index.php files. I understand that `is_front_page()` returns true when viewing the Site Front Page (whether displaying the blog posts index or a static page), while `is_home()` returns true when viewing the Blog Posts Index (whether displayed on the front page or on a static page). I am still somewhat stumped about the use of the following code - ``` <?php if ( have_posts() ) : ?> <?php if ( is_home() && ! is_front_page() ) : ?> <header> <h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1> </header> <?php endif; ?> ``` Any explanation of why this piece of code is so popular is greatly appreciated.
This will display the title of the **page** when a static page is set to show posts. **E.g.** I show posts on my homepage... It'll do nothing. If I, say, show posts on page titled **News**... It'll show **News** in H1. This is used so that the title of the page is shown, whenever posts are shown on a page, but nothing when blog posts are shown on the front page (home page). We do it because if it's on home page... it will show the title of the first post, making it appear twice (once at the top in H1 and again when posts are looped through).
224,632
<p>I create a widget for a custom post type that will display a list of post in the widget area. it works fine, i can select multiple posts and save the widget but i can not get it to display on the frontend. <strong>UPDATE</strong> so basically what i'm trying to achieve is list all the posts in the widget area with a checkbox (works fine), when a checkbox is checked it will show that post in the frontend, if checkbox isn't checked it will not show on the frontend. that s the part that isn't working, i get no coNtent output on the frontend <strong>HERE IS MY CODE</strong> </p> <pre><code> &lt;?php class mm_location_widget extends WP_Widget { function __construct() { parent::__construct( // Base ID of your widget 'mm_location_widget', // Widget name will appear in UI __('Locations By Marvil Media Widget', 'mm_location_widget_domain'), // Widget description array( 'description' =&gt; __( 'Locations Widget By Marvil Media', 'mm_location_widget_domain' ), ) ); } // Creating widget front-end // This is where the action happens public function widget( $args, $instance ) { $title = apply_filters( 'widget_title', $instance['title'] ); $your_checkbox_var = $instance[ 'your_checkbox_var' ] ? 'true' : 'false'; // before and after widget arguments are defined by themes echo $args['before_widget']; if ( ! empty( $title ) ) echo $args['before_title'] . $title . $args['after_title']; // This is where you run the code and display the output //echo __( 'Hello, World!', 'mm_location_widget_domain' ); // Retrieve the checkbox if ( $your_checkbox_var == 'checked' ) { $loc_id = $post-&gt;ID; $loc_title = get_the_title($post-&gt;ID); $loc_link = get_permalink($post-&gt;ID); $loc_address = get_post_meta( get_the_ID(), '_marvilmedia_address', true ); $loc_city = get_post_meta( get_the_ID(), '_marvilmedia_city', true ); $loc_state = get_post_meta( get_the_ID(), '_marvilmedia_state', true ); $loc_zipcode = get_post_meta( get_the_ID(), '_marvilmedia_zipcode', true ); $loc_phone = get_post_meta( get_the_ID(), '_marvilmedia_phone', true ); $loc_direction = get_post_meta( get_the_ID(), '_marvilmedia_direction', true ); // echo "&lt;ul&gt;"; foreach ($posts as $post) { $loc_info .= '&lt;div class="col-xs-12"&gt;'; $loc_info .= '&lt;h5&gt;&lt;a target="_blank" href="'.get_the_permalink().'"&gt;' . get_the_title() . '&lt;/a&gt;&lt;/h5&gt;'; $loc_info .= '&lt;p&gt;'; $loc_info .= $loc_address.'&lt;br/&gt;'; $loc_info .= $loc_city.',&amp;nbsp;'.$loc_state.'&amp;nbsp;'.$loc_zipcode.''; $loc_info .= $loc_phone.'&lt;br/&gt;'; $loc_info .= '&lt;/p&gt;'; $loc_info .= '&lt;/div&gt;'; echo $loc_info; } // echo "&lt;/ul&gt;"; }; ?&gt; &lt;?php // Retrieve the checkbox if( 'checked' == $instance[ 'your_checkbox_var' ] ) : $loc_id = $post-&gt;ID; $loc_title = get_the_title($post-&gt;ID); $loc_link = get_permalink($post-&gt;ID); $loc_address = get_post_meta( get_the_ID(), '_marvilmedia_address', true ); $loc_city = get_post_meta( get_the_ID(), '_marvilmedia_city', true ); $loc_state = get_post_meta( get_the_ID(), '_marvilmedia_state', true ); $loc_zipcode = get_post_meta( get_the_ID(), '_marvilmedia_zipcode', true ); $loc_phone = get_post_meta( get_the_ID(), '_marvilmedia_phone', true ); $loc_direction = get_post_meta( get_the_ID(), '_marvilmedia_direction', true ); // echo "&lt;ul&gt;"; foreach ($posts as $post) { $loc_info .= '&lt;div class="col-xs-12"&gt;'; $loc_info .= '&lt;h5&gt;&lt;a target="_blank" href="'.get_the_permalink().'"&gt;' . get_the_title() . '&lt;/a&gt;&lt;/h5&gt;'; $loc_info .= '&lt;p&gt;'; $loc_info .= $loc_address.'&lt;br/&gt;'; $loc_info .= $loc_city.',&amp;nbsp;'.$loc_state.'&amp;nbsp;'.$loc_zipcode.''; $loc_info .= $loc_phone.'&lt;br/&gt;'; $loc_info .= '&lt;/p&gt;'; $loc_info .= '&lt;/div&gt;'; echo $loc_info; } // echo "&lt;/ul&gt;"; endif; echo $args['after_widget']; } // Widget Backend public function form( $instance ) { if ( isset( $instance[ 'title' ] ) ) { $title = $instance[ 'title' ]; } else { $title = __( 'Locations', 'mm_location_widget_domain' ); } // Widget admin form ?&gt; &lt;p&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;"&gt;&lt;?php _e( 'Title:' ); ?&gt;&lt;/label&gt; &lt;input class="widefat" id="&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'title' ); ?&gt;" type="text" value="&lt;?php echo esc_attr( $title ); ?&gt;" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id( 'your_checkbox_var' ); ?&gt;"&gt;&lt;?php _e( 'Locations:' ); ?&gt;&lt;/label&gt;&lt;br/&gt; &lt;?php $args = array( 'post_type' =&gt; 'mm_location', 'posts_per_page' =&gt; -1, 'post_status' =&gt;'any', 'post_parent' =&gt; $post-&gt;ID ); $myposts = get_posts( $args ); foreach ( $myposts as $post ) { $option='&lt;input type="checkbox" id="'. $this-&gt;get_field_id( 'your_checkbox_var' ) .'[]" name="'. $this-&gt;get_field_name( 'your_checkbox_var' ) .'[]"'; //if (is_array($instance['your_checkbox_var'])) { foreach ($instance['your_checkbox_var'] as $posts) { if($posts==$post-&gt;ID) { $option=$option.=' checked="checked"'; } } //} $option .= ' value="'.$post-&gt;ID.'" /&gt;'; $option .= get_the_title($post-&gt;ID); $option .= '&lt;br /&gt;'; echo $option; } ?&gt; &lt;/p&gt; &lt;?php } // Updating widget replacing old instances with new public function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; $instance[ 'your_checkbox_var' ] = $new_instance[ 'your_checkbox_var' ]; return $instance; } } // Class mm_location_widget ends here // Register and load the widget function marvilmedia_loc_load_widget() { register_widget( 'mm_location_widget' ); } add_action( 'widgets_init', 'marvilmedia_loc_load_widget' ); ?&gt; </code></pre>
[ { "answer_id": 224649, "author": "Z. Zlatev", "author_id": 4192, "author_profile": "https://wordpress.stackexchange.com/users/4192", "pm_score": 2, "selected": true, "text": "<p>Without actually knowing what you're trying to achieve I see the following problems:</p>\n\n<ul>\n<li><code>$post</code> variable is not defined in your <code>widget()</code> method. Try setting it using <code>$post = get_post( get_the_ID() )</code> for instance.</li>\n<li>By the time you call <code>foreach ($posts as $post) { ... }</code> <code>$posts</code> variable is also not set. You need some query for this one I guess - <code>WP_Query()</code> or <code>get_posts()</code></li>\n</ul>\n\n<p>In order to effectively catch such problems set <code>WP_DEBUG</code> and <code>WP_DEBUG_LOG</code> constants both to <code>true</code> in your <code>wp-config.php</code> file then you'll be able to monitor <code>wp-content/debug.log</code> for notices and errors. Good luck.</p>\n" }, { "answer_id": 225658, "author": "sacgro", "author_id": 93512, "author_profile": "https://wordpress.stackexchange.com/users/93512", "pm_score": 0, "selected": false, "text": "<p>Here is what you are looking for:</p>\n\n<pre><code>&lt;?php\nclass mm_location_widget extends WP_Widget\n{\n function __construct()\n {\n parent::__construct(\n // Base ID of your widget\n 'mm_location_widget', \n // Widget name will appear in UI\n __('Locations By Marvil Media Widget', 'mm_location_widget_domain'), \n // Widget description\n array(\n 'description' =&gt; __('Locations Widget By Marvil Media', 'mm_location_widget_domain')\n ));\n }\n\n // Creating widget front-end\n // This is where the action happens\n public function widget($args, $instance)\n {\n $title = apply_filters('widget_title', $instance['title']);\n // $your_checkbox_var = $instance[ 'your_checkbox_var' ] ? 'true' : 'false';\n // before and after widget arguments are defined by themes\n echo $args['before_widget'];\n if (!empty($title))\n echo $args['before_title'] . $title . $args['after_title'];\n\n // This is where you run the code and display the output\n //echo __( 'Hello, World!', 'mm_location_widget_domain' );\n\n // Retrieve the checkbox\n $args1 = array(\n 'post_type' =&gt; 'mm_location',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n );\n\n $myposts = get_posts($args1);\n foreach ($myposts as $post) {\n $loc_info = \"\";\n $option = false;\n foreach ($instance['checkbox'] as $checks) {\n if ($checks == $post-&gt;ID) {\n $option = true;\n }\n }\n if ($option) {\n $loc_id = $post-&gt;ID;\n $loc_title = get_the_title($post-&gt;ID);\n $loc_link = get_permalink($post-&gt;ID);\n $loc_address = get_post_meta($loc_id, '_marvilmedia_address', true);\n $loc_city = get_post_meta($loc_id, '_marvilmedia_city', true);\n $loc_state = get_post_meta($loc_id, '_marvilmedia_state', true);\n $loc_zipcode = get_post_meta($loc_id, '_marvilmedia_zipcode', true);\n $loc_phone = get_post_meta($loc_id, '_marvilmedia_phone', true);\n $loc_direction = get_post_meta($loc_id, '_marvilmedia_direction', true);\n\n $loc_info .= '&lt;div class=\"col-xs-12\"&gt;';\n $loc_info .= '&lt;h5&gt;&lt;a target=\"_blank\" href=\"' . $loc_link . '\"&gt;' . $loc_title . '&lt;/a&gt;&lt;/h5&gt;';\n $loc_info .= '&lt;p&gt;';\n $loc_info .= $loc_address . '&lt;br/&gt;';\n $loc_info .= $loc_city . ',&amp;nbsp;' . $loc_state . '&amp;nbsp;' . $loc_zipcode . '';\n $loc_info .= $loc_phone . '&lt;br/&gt;';\n $loc_info .= '&lt;/p&gt;';\n $loc_info .= '&lt;/div&gt;';\n echo $loc_info;\n\n // echo \"&lt;/ul&gt;\";\n }\n ;\n }\n\n echo $args['after_widget'];\n }\n\n // Widget Backend \n public function form($instance)\n {\n if (isset($instance['title'])) {\n $title = $instance['title'];\n } else {\n $title = __('Locations', 'mm_location_widget_domain');\n }\n // Widget admin form\n ?&gt;\n\n &lt;p&gt;\n &lt;label for=\"&lt;?php\n echo $this-&gt;get_field_id('title');\n ?&gt;\"&gt;&lt;?php\n _e('Title:');\n ?&gt;&lt;/label&gt; \n &lt;input class=\"widefat\" id=\"&lt;?php\n echo $this-&gt;get_field_id('title');\n ?&gt;\" name=\"&lt;?php\n echo $this-&gt;get_field_name('title');\n ?&gt;\" type=\"text\" value=\"&lt;?php\n echo esc_attr($title);\n ?&gt;\" /&gt;\n &lt;/p&gt;\n\n &lt;p&gt;\n &lt;label for=\"&lt;?php\n echo $this-&gt;get_field_id('checkbox');\n ?&gt;\"&gt;&lt;?php\n _e('Locations:');\n ?&gt;&lt;/label&gt;&lt;br/&gt;\n &lt;?php\n $args = array(\n 'post_type' =&gt; 'mm_location',\n 'posts_per_page' =&gt; -1,\n 'post_status' =&gt; 'publish'\n );\n\n $myposts = get_posts($args);\n foreach ($myposts as $post) {\n $option = '&lt;input type=\"checkbox\" id=\"' . $this-&gt;get_field_id('checkbox') . '[]\" name=\"' . $this-&gt;get_field_name('checkbox') . '[]\"';\n $selected = $instance['checkbox'];\n $arrlength = count($selected);\n\n for ($x = 0; $x &lt; $arrlength; $x++) {\n if ($selected[$x] == $post-&gt;ID) {\n $option = $option .= ' checked=\"checked\"';\n }\n }\n //}\n $option .= ' value=\"' . $post-&gt;ID . '\" /&gt;';\n\n $option .= get_the_title($post-&gt;ID);\n $option .= '&lt;br /&gt;';\n echo $option;\n }\n ?&gt;\n &lt;/p&gt; \n\n &lt;?php\n }\n\n // Updating widget replacing old instances with new\n public function update($new_instance, $old_instance)\n {\n $instance = array();\n $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';\n $instance['checkbox'] = $new_instance['checkbox'];\n return $instance;\n }\n} // Class mm_location_widget ends here\n\n// Register and load the widget\nfunction marvilmedia_loc_load_widget()\n{\n register_widget('mm_location_widget');\n}\nadd_action('widgets_init', 'marvilmedia_loc_load_widget');\n</code></pre>\n" } ]
2016/04/24
[ "https://wordpress.stackexchange.com/questions/224632", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28580/" ]
I create a widget for a custom post type that will display a list of post in the widget area. it works fine, i can select multiple posts and save the widget but i can not get it to display on the frontend. **UPDATE** so basically what i'm trying to achieve is list all the posts in the widget area with a checkbox (works fine), when a checkbox is checked it will show that post in the frontend, if checkbox isn't checked it will not show on the frontend. that s the part that isn't working, i get no coNtent output on the frontend **HERE IS MY CODE** ``` <?php class mm_location_widget extends WP_Widget { function __construct() { parent::__construct( // Base ID of your widget 'mm_location_widget', // Widget name will appear in UI __('Locations By Marvil Media Widget', 'mm_location_widget_domain'), // Widget description array( 'description' => __( 'Locations Widget By Marvil Media', 'mm_location_widget_domain' ), ) ); } // Creating widget front-end // This is where the action happens public function widget( $args, $instance ) { $title = apply_filters( 'widget_title', $instance['title'] ); $your_checkbox_var = $instance[ 'your_checkbox_var' ] ? 'true' : 'false'; // before and after widget arguments are defined by themes echo $args['before_widget']; if ( ! empty( $title ) ) echo $args['before_title'] . $title . $args['after_title']; // This is where you run the code and display the output //echo __( 'Hello, World!', 'mm_location_widget_domain' ); // Retrieve the checkbox if ( $your_checkbox_var == 'checked' ) { $loc_id = $post->ID; $loc_title = get_the_title($post->ID); $loc_link = get_permalink($post->ID); $loc_address = get_post_meta( get_the_ID(), '_marvilmedia_address', true ); $loc_city = get_post_meta( get_the_ID(), '_marvilmedia_city', true ); $loc_state = get_post_meta( get_the_ID(), '_marvilmedia_state', true ); $loc_zipcode = get_post_meta( get_the_ID(), '_marvilmedia_zipcode', true ); $loc_phone = get_post_meta( get_the_ID(), '_marvilmedia_phone', true ); $loc_direction = get_post_meta( get_the_ID(), '_marvilmedia_direction', true ); // echo "<ul>"; foreach ($posts as $post) { $loc_info .= '<div class="col-xs-12">'; $loc_info .= '<h5><a target="_blank" href="'.get_the_permalink().'">' . get_the_title() . '</a></h5>'; $loc_info .= '<p>'; $loc_info .= $loc_address.'<br/>'; $loc_info .= $loc_city.',&nbsp;'.$loc_state.'&nbsp;'.$loc_zipcode.''; $loc_info .= $loc_phone.'<br/>'; $loc_info .= '</p>'; $loc_info .= '</div>'; echo $loc_info; } // echo "</ul>"; }; ?> <?php // Retrieve the checkbox if( 'checked' == $instance[ 'your_checkbox_var' ] ) : $loc_id = $post->ID; $loc_title = get_the_title($post->ID); $loc_link = get_permalink($post->ID); $loc_address = get_post_meta( get_the_ID(), '_marvilmedia_address', true ); $loc_city = get_post_meta( get_the_ID(), '_marvilmedia_city', true ); $loc_state = get_post_meta( get_the_ID(), '_marvilmedia_state', true ); $loc_zipcode = get_post_meta( get_the_ID(), '_marvilmedia_zipcode', true ); $loc_phone = get_post_meta( get_the_ID(), '_marvilmedia_phone', true ); $loc_direction = get_post_meta( get_the_ID(), '_marvilmedia_direction', true ); // echo "<ul>"; foreach ($posts as $post) { $loc_info .= '<div class="col-xs-12">'; $loc_info .= '<h5><a target="_blank" href="'.get_the_permalink().'">' . get_the_title() . '</a></h5>'; $loc_info .= '<p>'; $loc_info .= $loc_address.'<br/>'; $loc_info .= $loc_city.',&nbsp;'.$loc_state.'&nbsp;'.$loc_zipcode.''; $loc_info .= $loc_phone.'<br/>'; $loc_info .= '</p>'; $loc_info .= '</div>'; echo $loc_info; } // echo "</ul>"; endif; echo $args['after_widget']; } // Widget Backend public function form( $instance ) { if ( isset( $instance[ 'title' ] ) ) { $title = $instance[ 'title' ]; } else { $title = __( 'Locations', 'mm_location_widget_domain' ); } // Widget admin form ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'your_checkbox_var' ); ?>"><?php _e( 'Locations:' ); ?></label><br/> <?php $args = array( 'post_type' => 'mm_location', 'posts_per_page' => -1, 'post_status' =>'any', 'post_parent' => $post->ID ); $myposts = get_posts( $args ); foreach ( $myposts as $post ) { $option='<input type="checkbox" id="'. $this->get_field_id( 'your_checkbox_var' ) .'[]" name="'. $this->get_field_name( 'your_checkbox_var' ) .'[]"'; //if (is_array($instance['your_checkbox_var'])) { foreach ($instance['your_checkbox_var'] as $posts) { if($posts==$post->ID) { $option=$option.=' checked="checked"'; } } //} $option .= ' value="'.$post->ID.'" />'; $option .= get_the_title($post->ID); $option .= '<br />'; echo $option; } ?> </p> <?php } // Updating widget replacing old instances with new public function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; $instance[ 'your_checkbox_var' ] = $new_instance[ 'your_checkbox_var' ]; return $instance; } } // Class mm_location_widget ends here // Register and load the widget function marvilmedia_loc_load_widget() { register_widget( 'mm_location_widget' ); } add_action( 'widgets_init', 'marvilmedia_loc_load_widget' ); ?> ```
Without actually knowing what you're trying to achieve I see the following problems: * `$post` variable is not defined in your `widget()` method. Try setting it using `$post = get_post( get_the_ID() )` for instance. * By the time you call `foreach ($posts as $post) { ... }` `$posts` variable is also not set. You need some query for this one I guess - `WP_Query()` or `get_posts()` In order to effectively catch such problems set `WP_DEBUG` and `WP_DEBUG_LOG` constants both to `true` in your `wp-config.php` file then you'll be able to monitor `wp-content/debug.log` for notices and errors. Good luck.
224,633
<p>I want to add numbering to each image when I insert them into the post. For example if I insert 3 images into a post, there will be: </p> <ol> <li><p>Image 1 </p></li> <li><p>Image 2</p></li> <li><p>Image 3</p></li> </ol> <p>I looked through the WordPress documentation, but I can't find which hook is triggered when inserting images into a post. </p>
[ { "answer_id": 224635, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 4, "selected": true, "text": "<p>The <code>add_attachment</code> action is fired when the <code>wp_insert_attachment()</code> function is called to add an item to the media library. Images are added to posts after going into the media library first. Even when adding via the post editor, items are added to the library with <code>wp_insert_attachment()</code> then to the post.</p>\n\n<pre><code>add_action( 'add_attachment', function( $post_ID ) { \n // Do Stuff\n});\n</code></pre>\n\n<p>This will not allow you to number items by post, only by instance in the media library. Whether that works for your purposes, I cannot answer.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_attachment\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/add_attachment</a></p>\n" }, { "answer_id": 318644, "author": "Orun", "author_id": 18228, "author_profile": "https://wordpress.stackexchange.com/users/18228", "pm_score": 1, "selected": false, "text": "<p>If you actually want to hook into the point when the author of a post inserts an image or other attachment into the Wordpress editor, use <code>image_send_to_editor()</code></p>\n\n<p>For example, if you wanted to wrap the image in a <code>&lt;div&gt;</code> or <code>&lt;figure&gt;</code> each time, you could do it like this:</p>\n\n<pre><code>function wrap_attachments($html, $id, $caption, $title, $align, $url) {\n $src = wp_get_attachment_image_src( $id, $size, false );\n $output = \"&lt;div id='post-$id media-$id' class='align$align'&gt;\";\n $output .= \"&lt;img src='$src[0]' alt='$title' width='$src[1]' height='$src[2]' /&gt;\";\n $output .= \"&lt;/div&gt;\";\n return $output;\n}\nadd_filter( 'image_send_to_editor', 'wrap_attachments', 10, 9 );\n</code></pre>\n\n<p>Additional explanation <a href=\"https://css-tricks.com/snippets/wordpress/insert-images-within-figure-element-from-media-uploader/\" rel=\"nofollow noreferrer\">in this article</a>.</p>\n" }, { "answer_id": 413352, "author": "n0099", "author_id": 228702, "author_profile": "https://wordpress.stackexchange.com/users/228702", "pm_score": 1, "selected": false, "text": "<p>From 5.5.0, there's a new hook <a href=\"https://developer.wordpress.org/reference/hooks/wp_media_attach_action/\" rel=\"nofollow noreferrer\"><code>wp_media_attach_action</code></a> will monitor the event that fires after any attachment gets attached or detached more easily:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('wp_media_attach_action', function (string $action, int $attachment_id) {\n if ($action !== 'attach') return;\n // do your stuff\n});\n</code></pre>\n<p>Due to <code>at/detach</code> an attachment is just changing the value of <a href=\"https://developer.wordpress.org/reference/functions/get_post_parent/\" rel=\"nofollow noreferrer\"><code>post_parent</code></a> for its post, this hook still won't get fired after the author inserts the attachment into any post editor, for that you'll need <a href=\"https://developer.wordpress.org/reference/hooks/image_send_to_editor/\" rel=\"nofollow noreferrer\"><code>image_send_to_editor</code></a>, but this hook won't work when using gutenberg editor: <a href=\"https://github.com/danielbachhuber/gutenberg-migration-guide/blob/master/filter-image-send-to-editor.md\" rel=\"nofollow noreferrer\">https://github.com/danielbachhuber/gutenberg-migration-guide/blob/master/filter-image-send-to-editor.md</a> <a href=\"https://github.com/WordPress/gutenberg/issues/8472\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/issues/8472</a></p>\n<p>Even the <code>image_send_to_editor</code> still won't get fired when the author is not inserting attachments into the editor by selecting them from the media library, but just directly copying and pasting images or manually writing raw HTML <code>&lt;img&gt;</code> tags, if you must catch these cases, the hook <a href=\"https://developer.wordpress.org/reference/hooks/post_updated/\" rel=\"nofollow noreferrer\"><code>post_updated</code></a> might be your last resort.</p>\n" } ]
2016/04/24
[ "https://wordpress.stackexchange.com/questions/224633", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50610/" ]
I want to add numbering to each image when I insert them into the post. For example if I insert 3 images into a post, there will be: 1. Image 1 2. Image 2 3. Image 3 I looked through the WordPress documentation, but I can't find which hook is triggered when inserting images into a post.
The `add_attachment` action is fired when the `wp_insert_attachment()` function is called to add an item to the media library. Images are added to posts after going into the media library first. Even when adding via the post editor, items are added to the library with `wp_insert_attachment()` then to the post. ``` add_action( 'add_attachment', function( $post_ID ) { // Do Stuff }); ``` This will not allow you to number items by post, only by instance in the media library. Whether that works for your purposes, I cannot answer. <https://codex.wordpress.org/Plugin_API/Action_Reference/add_attachment>
224,645
<p>I tried to filter only the text in <code>get_the_content</code> for my home page, but its including my shortcode also, because in that page first row google map 2nd row text box i am using visual composer page builder.</p> <p><strong>My code</strong></p> <pre><code>$content = get_the_content(); $content = apply_filters('the_content', substr(get_the_content(), 0, 60) ); $content = str_replace(']]&gt;', ']]&amp;gt;', $content); echo $content </code></pre> <p><strong>My result</strong></p> <blockquote> <p>[vc_row][vc_column][vc_gmaps link=&#8221;#E-8_JTNDaWZyYW1lJTIwc3Jj</p> </blockquote> <p>screenshot</p> <p><a href="https://i.stack.imgur.com/RktDI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RktDI.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 224650, "author": "Tim Malone", "author_id": 46066, "author_profile": "https://wordpress.stackexchange.com/users/46066", "pm_score": 1, "selected": false, "text": "<p>Based on your comment clarifying what you want to achieve, it appears you want to display the first 60 characters of your post <em>not including any shortcodes</em>.</p>\n\n<p>To do this you can use the <code>strip_shortcodes()</code> function. Rewritten with that, your code will look like this:</p>\n\n<pre><code>$content = strip_shortcodes(get_the_content());\n$content = apply_filters('the_content', substr($content, 0, 60) );\n$content = str_replace(']]&gt;', ']]&amp;gt;', $content);\necho $content;\n</code></pre>\n\n<p>All we're doing here is running the content (from <code>get_the_content()</code>) through <code>strip_shortcodes()</code> before applying Wordpress filters on the first 60 characters.</p>\n\n<p>Depending on what you want to achieve and whether you're relying on any other plugins modifying this content for you, you actually might be fine to skip the <code>apply_filters()</code> call as well - in which case all you'd need to do is set <code>$content</code> to the <code>substr()</code> you want to have.</p>\n" }, { "answer_id": 232329, "author": "Patidar Sam", "author_id": 98359, "author_profile": "https://wordpress.stackexchange.com/users/98359", "pm_score": -1, "selected": false, "text": "<p>You can use </p>\n\n<pre><code>do_shortcode(get_the_content($id)); \n</code></pre>\n\n<p>instead</p>\n" } ]
2016/04/24
[ "https://wordpress.stackexchange.com/questions/224645", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85768/" ]
I tried to filter only the text in `get_the_content` for my home page, but its including my shortcode also, because in that page first row google map 2nd row text box i am using visual composer page builder. **My code** ``` $content = get_the_content(); $content = apply_filters('the_content', substr(get_the_content(), 0, 60) ); $content = str_replace(']]>', ']]&gt;', $content); echo $content ``` **My result** > > [vc\_row][vc\_column][vc\_gmaps > link=”#E-8\_JTNDaWZyYW1lJTIwc3Jj > > > screenshot [![enter image description here](https://i.stack.imgur.com/RktDI.jpg)](https://i.stack.imgur.com/RktDI.jpg)
Based on your comment clarifying what you want to achieve, it appears you want to display the first 60 characters of your post *not including any shortcodes*. To do this you can use the `strip_shortcodes()` function. Rewritten with that, your code will look like this: ``` $content = strip_shortcodes(get_the_content()); $content = apply_filters('the_content', substr($content, 0, 60) ); $content = str_replace(']]>', ']]&gt;', $content); echo $content; ``` All we're doing here is running the content (from `get_the_content()`) through `strip_shortcodes()` before applying Wordpress filters on the first 60 characters. Depending on what you want to achieve and whether you're relying on any other plugins modifying this content for you, you actually might be fine to skip the `apply_filters()` call as well - in which case all you'd need to do is set `$content` to the `substr()` you want to have.
224,661
<p>Why is there a constant notice,</p> <blockquote> <p>JQMIGRATE: Migrate is installed, version 1.4.0</p> </blockquote> <p>that points to <code>load-scripts.php</code> in my console when I updated my theme to WordPress 4.5, and how can it be removed?</p> <p>It's not an error, but it's always present in my console, and I really don't see what's the point of it. Should I update something, or make some changes to my code?</p> <p>Maybe I have a bit of OCD, but usually when I inspect the site, I like to see errors and real notices that point to an issue in my console...</p> <h3>EDIT</h3> <p>WordPress 5.5 removed jQuery Migrate script, as a preparation step for updating jQuery to the latest version in 5.6. So the notice should be gone.</p> <p><a href="https://make.wordpress.org/core/2020/06/29/updating-jquery-version-shipped-with-wordpress/" rel="noreferrer">https://make.wordpress.org/core/2020/06/29/updating-jquery-version-shipped-with-wordpress/</a></p>
[ { "answer_id": 224666, "author": "Andy", "author_id": 43719, "author_profile": "https://wordpress.stackexchange.com/users/43719", "pm_score": 7, "selected": true, "text": "<p>WordPress uses the jQuery migrate script to ensure backwards compatibility for any plugins or themes you might be using which use functionality removed from newer versions of jQuery.</p>\n<p>With the release of WordPress 4.5, it appears they have upgraded the version of jQuery migrate from <a href=\"http://code.jquery.com/jquery-migrate-1.2.1.min.js\" rel=\"noreferrer\">v1.2.1</a> to <a href=\"http://code.jquery.com/jquery-migrate-1.4.0.min.js\" rel=\"noreferrer\">v1.4.0</a> - Having a quick scan through the code reveals that v1.4.0 logs that the script is loaded regardless of whether or not the <code>migrateMute</code> option is set, in both the uncompressed <em>and</em> minified versions.</p>\n<p>The only way to remove the notice is to ensure all your plugins/theme code don't rely on any old jQuery functionality, and then remove the migrate script. There's a <a href=\"https://github.com/cedaro/dequeue-jquery-migrate/blob/develop/dequeue-jquery-migrate.php\" rel=\"noreferrer\">plugin</a> out there to do this, but it's quite a simple method that can just be placed in your theme's functions file or similar:</p>\n<pre><code>add_action('wp_default_scripts', function ($scripts) {\n if (!empty($scripts-&gt;registered['jquery'])) {\n $scripts-&gt;registered['jquery']-&gt;deps = array_diff($scripts-&gt;registered['jquery']-&gt;deps, ['jquery-migrate']);\n }\n});\n</code></pre>\n<p>Please note that this is not considered best practice for WordPress development and in my opinion the migrate script should not be removed just for the sake of keeping the developer console clean.</p>\n" }, { "answer_id": 224719, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": false, "text": "<p>You could change the log message text to blank in <code>jquery-migrate.min.js</code> but this will not be preserved on core update.</p>\n\n<p>The alternative is to add passthrough/filter function copy of <code>console.log</code> to just before the migrate script is loaded, and tell it to ignore logging messages that contain '<code>Migrate is installed</code>'. Doing it this way will preserve other Migrate warnings too:</p>\n\n<pre><code>// silencer script\nfunction jquery_migrate_silencer() {\n // create function copy\n $silencer = '&lt;script&gt;window.console.logger = window.console.log; ';\n // modify original function to filter and use function copy\n $silencer .= 'window.console.log = function(tolog) {';\n // bug out if empty to prevent error\n $silencer .= 'if (tolog == null) {return;} ';\n // filter messages containing string\n $silencer .= 'if (tolog.indexOf(\"Migrate is installed\") == -1) {';\n $silencer .= 'console.logger(tolog);} ';\n $silencer .= '}&lt;/script&gt;';\n return $silencer;\n}\n\n// for the frontend, use script_loader_tag filter\nadd_filter('script_loader_tag','jquery_migrate_load_silencer', 10, 2);\nfunction jquery_migrate_load_silencer($tag, $handle) {\n if ($handle == 'jquery-migrate') {\n $silencer = jquery_migrate_silencer();\n // prepend to jquery migrate loading\n $tag = $silencer.$tag;\n }\n return $tag;\n}\n\n// for the admin, hook to admin_print_scripts\nadd_action('admin_print_scripts','jquery_migrate_echo_silencer');\nfunction jquery_migrate_echo_silencer() {echo jquery_migrate_silencer();}\n</code></pre>\n\n<p>The result is a one line of HTML script added to both frontend and backend that achieves the desired effect (prevents the installed message.)</p>\n" }, { "answer_id": 224725, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p>Just a little test here.</p>\n\n<p>I peeked into <a href=\"http://code.jquery.com/jquery-migrate-1.4.0.js\" rel=\"noreferrer\">jquery-migrate.js</a> and noticed this part:</p>\n\n<pre><code>// Set to true to prevent console output; migrateWarnings still maintained\n// jQuery.migrateMute = false;\n</code></pre>\n\n<p>so I tested the following with the newly <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"noreferrer\"><code>wp_add_inline_script()</code></a>, introduced in version 4.5:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function()\n{ \n wp_add_inline_script( \n 'jquery-migrate', 'jQuery.migrateMute = true;',\n 'before' \n );\n} );\n</code></pre>\n\n<p>This will change: </p>\n\n<blockquote>\n <p>JQMIGRATE: Migrate is installed with\n logging active, version 1.4.0</p>\n</blockquote>\n\n<p>to:</p>\n\n<blockquote>\n <p>JQMIGRATE: Migrate is installed, version 1.4.0</p>\n</blockquote>\n\n<p>So it doesn't actually prevent all console output, like this part in <code>jquery-migrate.js</code>:</p>\n\n<pre><code>// Show a message on the console so devs know we're active\nif ( window.console &amp;&amp; window.console.log ) {\n window.console.log( \"JQMIGRATE: Migrate is installed\" +\n ( jQuery.migrateMute ? \"\" : \" with logging active\" ) +\n \", version \" + jQuery.migrateVersion );\n}\n</code></pre>\n" }, { "answer_id": 301975, "author": "Guy Dumais Digital", "author_id": 142531, "author_profile": "https://wordpress.stackexchange.com/users/142531", "pm_score": -1, "selected": false, "text": "<p><p>As mentionned previously by Andy <strong><em>WordPress uses the jQuery migrate script to ensure backwards compatibility</em></strong> and this is why it is automatically loaded by default.<p>\n<p>Here's a safe way to remove the JQuery Migrate module and thus get rid of the annoying JQMIGRATE notice while speeding up the loading of your page on the client side. Simply copy/paste this code in your <strong>functions.php</strong> file and you're done:<br/></p>\n\n<pre><code>&lt;?php\n/**\n * Disable jQuery Migrate in WordPress.\n *\n * @author Guy Dumais.\n * @link https://en.guydumais.digital/disable-jquery-migrate-in-wordpress/\n */\nadd_filter( 'wp_default_scripts', $af = static function( &amp;$scripts) {\n if(!is_admin()) {\n $scripts-&gt;remove( 'jquery');\n $scripts-&gt;add( 'jquery', false, array( 'jquery-core' ), '1.12.4' );\n } \n}, PHP_INT_MAX );\nunset( $af );\n</code></pre>\n\n<p><br/></p>\n\n<h2>More details</h2>\n\n<p><p>To get more details about the reason I'm using a static function, read my article here:<br/>\n►► <a href=\"https://en.guydumais.digital/disable-jquery-migrate-in-wordpress/\" rel=\"nofollow noreferrer\">https://en.guydumais.digital/disable-jquery-migrate-in-wordpress/</a></p>\n" }, { "answer_id": 312560, "author": "Yuri", "author_id": 149434, "author_profile": "https://wordpress.stackexchange.com/users/149434", "pm_score": 1, "selected": false, "text": "<p>Had the same problem, and found out you just need to set <code>SCRIPT_DEBUG</code> to <code>false</code> in your <code>wp-config.php</code>. Hope this helps someone</p>\n" }, { "answer_id": 314803, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 3, "selected": false, "text": "<h1>Solution:</h1>\n\n<p>add this to functions.php:</p>\n\n<pre><code>function remove_jquery_migrate_notice() {\n $m= $GLOBALS['wp_scripts']-&gt;registered['jquery-migrate'];\n $m-&gt;extra['before'][]='temp_jm_logconsole = window.console.log; window.console.log=null;';\n $m-&gt;extra['after'][]='window.console.log=temp_jm_logconsole;';\n}\nadd_action( 'init', 'remove_jquery_migrate_notice', 5 );\n</code></pre>\n\n<p>It works when <code>jquery-migrate</code> is called with standard hook (which outputs <code>&lt;link rel=stylesheet....&gt;</code>) and not with <code>load-scripts.php</code> in bulk (like in admin-dashboard).</p>\n" }, { "answer_id": 404155, "author": "Christopher S.", "author_id": 127679, "author_profile": "https://wordpress.stackexchange.com/users/127679", "pm_score": 1, "selected": false, "text": "<p><strong>Just modify your Inspector Console when needed</strong></p>\n<p>Instead of hardcoding anything in your website, most inspectors give you method to edit the console output locally.</p>\n<p><strong>For Chrome and Opera</strong></p>\n<p>Using inspector console you can <strong>right click</strong> on the <code>JQMIGRATE ...</code> Warning and <strong>click 'Hide messages from jquery-migrate.js'</strong>.</p>\n<p>Console Filter</p>\n<p>This will add <code>'-url:&lt;YOUR_WORDPRESS_URL&gt;/wp-includes/js/jquery/jquery-migrate.js?ver=3.3.2'</code> to the console filter. Effectively subtracting this url from the console output.</p>\n<p><em>Note: if you copying the above to the filters change out <code>&lt;YOUR_WORDPRESS_URL&gt;</code> for your wp url</em></p>\n<p>This console filter is persistently applied to new tabs and windows as well.</p>\n<p><strong>Safari</strong></p>\n<p>For Safari you can create an inspector <a href=\"https://webkit.org/web-inspector/local-overrides/\" rel=\"nofollow noreferrer\">Response Local Override</a> pretty easily.</p>\n<p><strong>Right click</strong> on the <code>jquery-migrate.js:line</code> to the right of the console log outputs, then select 'Create Response Local Override'.</p>\n<p>Which means you edit the file locally for dev purposes. So to remove these migrate notices add this to the top of the <code>jquery-migrate.js</code> file in your Response Local Override.</p>\n<pre><code>/**\n * Response Local Override\n */\njQuery.migrateMute = true;\n</code></pre>\n<p><strong>Firefox</strong></p>\n<p>Local overrides not supported currently. <a href=\"https://support.mozilla.org/en-US/questions/1331771\" rel=\"nofollow noreferrer\">https://support.mozilla.org/en-US/questions/1331771</a></p>\n<p>Tab/Window Based Filter Console output</p>\n<p>type <code>-jquery-migrate.js</code> into the 'Filter Output' bar and Jquery migrate notices will disappear even on reload of tab.</p>\n<p><em>Caveat: this console filter will need to be applied each time you open a new firefox tab or window.</em></p>\n<p>Hope this helps!</p>\n" } ]
2016/04/24
[ "https://wordpress.stackexchange.com/questions/224661", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58895/" ]
Why is there a constant notice, > > JQMIGRATE: Migrate is installed, version 1.4.0 > > > that points to `load-scripts.php` in my console when I updated my theme to WordPress 4.5, and how can it be removed? It's not an error, but it's always present in my console, and I really don't see what's the point of it. Should I update something, or make some changes to my code? Maybe I have a bit of OCD, but usually when I inspect the site, I like to see errors and real notices that point to an issue in my console... ### EDIT WordPress 5.5 removed jQuery Migrate script, as a preparation step for updating jQuery to the latest version in 5.6. So the notice should be gone. <https://make.wordpress.org/core/2020/06/29/updating-jquery-version-shipped-with-wordpress/>
WordPress uses the jQuery migrate script to ensure backwards compatibility for any plugins or themes you might be using which use functionality removed from newer versions of jQuery. With the release of WordPress 4.5, it appears they have upgraded the version of jQuery migrate from [v1.2.1](http://code.jquery.com/jquery-migrate-1.2.1.min.js) to [v1.4.0](http://code.jquery.com/jquery-migrate-1.4.0.min.js) - Having a quick scan through the code reveals that v1.4.0 logs that the script is loaded regardless of whether or not the `migrateMute` option is set, in both the uncompressed *and* minified versions. The only way to remove the notice is to ensure all your plugins/theme code don't rely on any old jQuery functionality, and then remove the migrate script. There's a [plugin](https://github.com/cedaro/dequeue-jquery-migrate/blob/develop/dequeue-jquery-migrate.php) out there to do this, but it's quite a simple method that can just be placed in your theme's functions file or similar: ``` add_action('wp_default_scripts', function ($scripts) { if (!empty($scripts->registered['jquery'])) { $scripts->registered['jquery']->deps = array_diff($scripts->registered['jquery']->deps, ['jquery-migrate']); } }); ``` Please note that this is not considered best practice for WordPress development and in my opinion the migrate script should not be removed just for the sake of keeping the developer console clean.
224,670
<p>I use this to display the featured image for each post. If the post does not have a featured image, a generic image will be displayed:</p> <pre><code>&lt;?php if ( has_post_thumbnail() ) { echo '&lt;a href="' . get_permalink($post-&gt;ID) . '" &gt;'; the_post_thumbnail(); echo '&lt;/a&gt;'; } else { echo '&lt;img src="&lt;?php bloginfo('template_directory'); ?&gt;/img/fallback-featured-image.jpg" /&gt;'; } </code></pre> <p>How can I get the fallback image to link to the permalink?</p>
[ { "answer_id": 224672, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 1, "selected": false, "text": "<p>The problem is when you are trying to get the template directory. You are <code>getting</code> it instead of <code>printing</code></p>\n\n<p><code>bloginfo()</code> <strong>prints</strong> the output</p>\n\n<p><code>get_bloginfo()</code> <strong>retrieves</strong> the output</p>\n\n<p>So, the nice piece of code should look like this:</p>\n\n<pre><code>&lt;?php\n\nif ( has_post_thumbnail() ) {\n echo '&lt;a href=\"' . get_permalink($post-&gt;ID) . '\" &gt;';\n the_post_thumbnail();\n echo '&lt;/a&gt;';\n} else {\n echo '&lt;img src=\"';\n echo get_bloginfo('template_directory');\n echo '/img/fallback-featured-image.jpg\" /&gt;';\n}\n</code></pre>\n" }, { "answer_id": 224673, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 3, "selected": true, "text": "<p>I have updated your code so that the fallback image has post permalink. I hope this helps:</p>\n\n<pre><code>if ( has_post_thumbnail() ) {\n echo '&lt;a href=\"' . get_permalink($post-&gt;ID) . '\" &gt;';\n the_post_thumbnail();\n echo '&lt;/a&gt;';\n} else {\n echo '&lt;a href=\"' . get_permalink($post-&gt;ID) . '\" &gt;&lt;img src=\"'. get_stylesheet_directory_uri() . '/img/fallback-featured-image.jpg\" /&gt;&lt;/a&gt;';\n}\n</code></pre>\n" } ]
2016/04/24
[ "https://wordpress.stackexchange.com/questions/224670", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82313/" ]
I use this to display the featured image for each post. If the post does not have a featured image, a generic image will be displayed: ``` <?php if ( has_post_thumbnail() ) { echo '<a href="' . get_permalink($post->ID) . '" >'; the_post_thumbnail(); echo '</a>'; } else { echo '<img src="<?php bloginfo('template_directory'); ?>/img/fallback-featured-image.jpg" />'; } ``` How can I get the fallback image to link to the permalink?
I have updated your code so that the fallback image has post permalink. I hope this helps: ``` if ( has_post_thumbnail() ) { echo '<a href="' . get_permalink($post->ID) . '" >'; the_post_thumbnail(); echo '</a>'; } else { echo '<a href="' . get_permalink($post->ID) . '" ><img src="'. get_stylesheet_directory_uri() . '/img/fallback-featured-image.jpg" /></a>'; } ```
224,735
<p>I have a WordPress Multisite that uses a special query that combines all the posts on the network and uses the main site to display all posts in the network. </p> <p>Anyway, I would like to have my site use infinite scroll. No matter what plugins I use, it won't use infinite scroll. </p> <p>Here's how the query works on my site: </p> <pre><code>&lt;?php get_header(); ?&gt; &lt;section id="index"&gt; &lt;div class="container"&gt; &lt;div class="main"&gt; &lt;?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'multisite' =&gt; 1, 'sites__not_in' =&gt; array(1), 'paged' =&gt; $paged, ); $query = new WP_Query( $args ); while($query-&gt;have_posts()) : $query-&gt;the_post(); ?&gt; &lt;?php get_template_part( 'content', get_post_format() ); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php if (is_front_page() ) { ?&gt; &lt;nav id="first-nav"&gt; &lt;?php next_posts_link( 'load more', $query-&gt;max_num_pages ); ?&gt; &lt;/nav&gt; &lt;?php } else { ;?&gt; &lt;nav id="navigate"&gt; &lt;?php previous_posts_link( 'Previous' );next_posts_link( 'Next', $query-&gt;max_num_pages ); ?&gt; &lt;/nav&gt; &lt;?php } ?&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;?php get_footer();?&gt; </code></pre> <p>Any ideas on how to get this to work?</p>
[ { "answer_id": 224672, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 1, "selected": false, "text": "<p>The problem is when you are trying to get the template directory. You are <code>getting</code> it instead of <code>printing</code></p>\n\n<p><code>bloginfo()</code> <strong>prints</strong> the output</p>\n\n<p><code>get_bloginfo()</code> <strong>retrieves</strong> the output</p>\n\n<p>So, the nice piece of code should look like this:</p>\n\n<pre><code>&lt;?php\n\nif ( has_post_thumbnail() ) {\n echo '&lt;a href=\"' . get_permalink($post-&gt;ID) . '\" &gt;';\n the_post_thumbnail();\n echo '&lt;/a&gt;';\n} else {\n echo '&lt;img src=\"';\n echo get_bloginfo('template_directory');\n echo '/img/fallback-featured-image.jpg\" /&gt;';\n}\n</code></pre>\n" }, { "answer_id": 224673, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 3, "selected": true, "text": "<p>I have updated your code so that the fallback image has post permalink. I hope this helps:</p>\n\n<pre><code>if ( has_post_thumbnail() ) {\n echo '&lt;a href=\"' . get_permalink($post-&gt;ID) . '\" &gt;';\n the_post_thumbnail();\n echo '&lt;/a&gt;';\n} else {\n echo '&lt;a href=\"' . get_permalink($post-&gt;ID) . '\" &gt;&lt;img src=\"'. get_stylesheet_directory_uri() . '/img/fallback-featured-image.jpg\" /&gt;&lt;/a&gt;';\n}\n</code></pre>\n" } ]
2016/04/25
[ "https://wordpress.stackexchange.com/questions/224735", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8049/" ]
I have a WordPress Multisite that uses a special query that combines all the posts on the network and uses the main site to display all posts in the network. Anyway, I would like to have my site use infinite scroll. No matter what plugins I use, it won't use infinite scroll. Here's how the query works on my site: ``` <?php get_header(); ?> <section id="index"> <div class="container"> <div class="main"> <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'multisite' => 1, 'sites__not_in' => array(1), 'paged' => $paged, ); $query = new WP_Query( $args ); while($query->have_posts()) : $query->the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile; ?> <?php if (is_front_page() ) { ?> <nav id="first-nav"> <?php next_posts_link( 'load more', $query->max_num_pages ); ?> </nav> <?php } else { ;?> <nav id="navigate"> <?php previous_posts_link( 'Previous' );next_posts_link( 'Next', $query->max_num_pages ); ?> </nav> <?php } ?> <?php wp_reset_postdata(); ?> </div> </div> </section> <?php get_footer();?> ``` Any ideas on how to get this to work?
I have updated your code so that the fallback image has post permalink. I hope this helps: ``` if ( has_post_thumbnail() ) { echo '<a href="' . get_permalink($post->ID) . '" >'; the_post_thumbnail(); echo '</a>'; } else { echo '<a href="' . get_permalink($post->ID) . '" ><img src="'. get_stylesheet_directory_uri() . '/img/fallback-featured-image.jpg" /></a>'; } ```
224,748
<p>I've got a custom post type called productpopups, and to sort them I have a custom taxonomy called productcategory. The post type has it's own special template (single-productpopup.php) and I'm trying to show each products category with a link to the category. The problem I have is the following:</p> <p>The link for each productcategory is say <code>example.com/productcategory/category</code> but the page I want to link it to is actually <code>example.com/category</code></p> <p>So I made up this:</p> <pre><code>&lt;p&gt;Categories: &lt;?php $categories = get_the_terms( $post-&gt;ID, 'productcategory' ); foreach( $categories as $category ) { echo '&lt;a href="http://example.com/'.$category-&gt;slug.'"&gt;'.$category-&gt;name.'&lt;/a&gt;, '; } ?&gt; &lt;/p&gt; </code></pre> <p>This works because the pages I have set up use the same slugs as the productcategory, but its hacky and one slip (like a typo) will break it.</p> <p>What I'd essential like to do is add a custom field to the taxonomy where I can specify the page url, and then be able to call that instead of the <code>http://example.com/.$category-&gt;slug</code></p> <p>Is this possible?</p> <p><strong>Edit for additional clarification:</strong> Forget the fact it's a url, I need a field where I can input data, and can be queried on a by product basis, so that if a product has multiple categories, the information for each can be found. For example say Product A has two categories, one and two, a table like this would be able to be formed:</p> <pre><code>+-----------+----------+--------------+ | Name | Category | Custom Value | +-----------+----------+--------------+ | Product A | C 001 | CV 001 | +-----------+----------+--------------+ | Product A | C 002 | CV 002 | +-----------+----------+--------------+ </code></pre>
[ { "answer_id": 224768, "author": "Victor", "author_id": 92972, "author_profile": "https://wordpress.stackexchange.com/users/92972", "pm_score": 0, "selected": false, "text": "<p>If you created the taxonomy yourself, you could set your own slug for the custom taxonomy. For Example:</p>\n\n<pre><code>register_taxonomy(\n 'productcategory',\n array(\n 'productpopups',\n ),\n array(\n 'labels' =&gt; array(\n 'name' =&gt; __('Categories', 'text-domain'),\n ),\n\n // --- set taxonomy slug ---\n 'rewrite' =&gt; array(\n 'slug' =&gt; '%productcategory%', // set taxonomy slug\n 'with_front' =&gt; false, // set this to false\n )\n // -------------------------\n )\n);\n\nflush_rewrite_rules(); // &lt;-- don't forget to add this line of code!\n</code></pre>\n" }, { "answer_id": 225191, "author": "CalvT", "author_id": 56659, "author_profile": "https://wordpress.stackexchange.com/users/56659", "pm_score": 1, "selected": true, "text": "<p>The code that I finally came up with to fix the problem!</p>\n\n<pre><code>&lt;?php\nglobal $wpdb;\n$catresult = array();\n$postid = get_the_ID();\n$query1c = \"SELECT wp_posts.ID, wp_terms.`name` AS `Category`, wp_pods_productcategory.`pc-url` AS `Url`\nFROM wp_posts\nINNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id\nINNER JOIN wp_terms ON wp_term_relationships.term_taxonomy_id = wp_terms.term_id\nLEFT OUTER JOIN wp_pods_productcategory ON wp_pods_productcategory.id = wp_term_relationships.term_taxonomy_id\nINNER JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_id\nWHERE wp_term_taxonomy.taxonomy = 'productcategory' AND wp_posts.ID =$postid\nORDER BY wp_terms.`name` ASC\";\n$categories = $wpdb-&gt;get_results( $query1c );\nforeach ( $categories as $category )\n{\narray_push( $catresult, \"&lt;a href='\".$category-&gt;Url.\"'&gt;\".$category-&gt;Category.\"&lt;/a&gt;\" );\n}\necho implode(', ', $catresult);\n?&gt;\n</code></pre>\n\n<p>So how does this work?</p>\n\n<p><code>&lt;?php</code> This is the opening tag so the server knows what comes next is <code>php</code>.</p>\n\n<p><code>global $wpdb</code> Here we tell the server that we'll be connecting to the WordPress Database.</p>\n\n<p><code>$catresult = array();</code> Here we create the array we'll use to store the data.</p>\n\n<p><code>$postid = get_the_ID();</code> Here we get the post id to be able to filter the query.</p>\n\n<p><code>$query1c = \"SELECT....</code> Here we put the query, which selects the fields we want, filtered by <code>wp_term_taxonomy.taxonomy = 'productcategory'</code> and <code>wp_posts.ID =$postid</code> (this is where we use the <code>$postid</code> from before) and ordered by <code>wp_terms.name ASC</code>.</p>\n\n<p><code>$categories = $wpdb-&gt;get_results( $query1c )</code> This runs the query, and saves the raw data to <code>$categories</code>.</p>\n\n<p>Now we need to convert the raw data into something we can use, the raw data is currently saved as <code>$categories</code> but we need each result individually so we put:</p>\n\n<p><code>foreach ( $categories as $category)</code> Here one result gets known as <code>$category</code></p>\n\n<p><code>array_push( $catresult, \"&lt;a href='\".$category-&gt;Url.\"'&gt;\".$category-&gt;Category.\"&lt;/a&gt;\" )</code> Here we 'push' each result individually to the array we created earlier - <code>$catresult</code>. Each result has been prepared with its link (<code>&lt;a&gt;</code> tag).</p>\n\n<p>One last thing - as we want these categories in a list, it would look better if they where separated by commas! So:</p>\n\n<p><code>echo implode(', ', $catresult)</code> So here we 'implode' the array, which means we put something between each result of the array, which in this case is a comma followed by a space. This is then printed to the page by using the <code>echo</code> command.</p>\n\n<p>Finally <code>?&gt;</code> tells the server to close this <code>php</code> section.</p>\n" }, { "answer_id": 284088, "author": "omukiguy", "author_id": 102683, "author_profile": "https://wordpress.stackexchange.com/users/102683", "pm_score": 2, "selected": false, "text": "<p>Sorry to come to the party late. Here is my solution</p>\n\n<pre><code>&lt;?php\n //Retrieve the terms in productcategory taxonomy with posts (not empty)\n $terms = get_terms( array ( 'taxonomy' =&gt; 'productcategory', 'hide_empty' =&gt; false, 'parent' =&gt; 0, 'orderby' =&gt; 'description', 'order' =&gt; 'ASC' ));\n\n //loop through each term to get its attributes\n foreach ($terms as $term) {\n\n //Uncomment below code to see all the available attributes.\n //var_dump($term); \n //die();\n $name = $term-&gt;name;\n\n //PHP -&gt; Store the link in variable to reuse\n //to get the link for the the particular term; you need to have the slug and pass it into the get_term_link() function.\n //the second argument is the taxonomy name in this case productcategory.\n $cat_link = get_term_link( $term-&gt;slug, 'productcategory' );\n\n?&gt;\n\n&lt;a href=\"&lt;?php echo $cat_link; ?&gt;\"&gt;&lt;?php echo $name; ?&gt;&lt;/a&gt;\n\n&lt;?php\n }\n\n?&gt;\n</code></pre>\n" } ]
2016/04/25
[ "https://wordpress.stackexchange.com/questions/224748", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56659/" ]
I've got a custom post type called productpopups, and to sort them I have a custom taxonomy called productcategory. The post type has it's own special template (single-productpopup.php) and I'm trying to show each products category with a link to the category. The problem I have is the following: The link for each productcategory is say `example.com/productcategory/category` but the page I want to link it to is actually `example.com/category` So I made up this: ``` <p>Categories: <?php $categories = get_the_terms( $post->ID, 'productcategory' ); foreach( $categories as $category ) { echo '<a href="http://example.com/'.$category->slug.'">'.$category->name.'</a>, '; } ?> </p> ``` This works because the pages I have set up use the same slugs as the productcategory, but its hacky and one slip (like a typo) will break it. What I'd essential like to do is add a custom field to the taxonomy where I can specify the page url, and then be able to call that instead of the `http://example.com/.$category->slug` Is this possible? **Edit for additional clarification:** Forget the fact it's a url, I need a field where I can input data, and can be queried on a by product basis, so that if a product has multiple categories, the information for each can be found. For example say Product A has two categories, one and two, a table like this would be able to be formed: ``` +-----------+----------+--------------+ | Name | Category | Custom Value | +-----------+----------+--------------+ | Product A | C 001 | CV 001 | +-----------+----------+--------------+ | Product A | C 002 | CV 002 | +-----------+----------+--------------+ ```
The code that I finally came up with to fix the problem! ``` <?php global $wpdb; $catresult = array(); $postid = get_the_ID(); $query1c = "SELECT wp_posts.ID, wp_terms.`name` AS `Category`, wp_pods_productcategory.`pc-url` AS `Url` FROM wp_posts INNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id INNER JOIN wp_terms ON wp_term_relationships.term_taxonomy_id = wp_terms.term_id LEFT OUTER JOIN wp_pods_productcategory ON wp_pods_productcategory.id = wp_term_relationships.term_taxonomy_id INNER JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_id WHERE wp_term_taxonomy.taxonomy = 'productcategory' AND wp_posts.ID =$postid ORDER BY wp_terms.`name` ASC"; $categories = $wpdb->get_results( $query1c ); foreach ( $categories as $category ) { array_push( $catresult, "<a href='".$category->Url."'>".$category->Category."</a>" ); } echo implode(', ', $catresult); ?> ``` So how does this work? `<?php` This is the opening tag so the server knows what comes next is `php`. `global $wpdb` Here we tell the server that we'll be connecting to the WordPress Database. `$catresult = array();` Here we create the array we'll use to store the data. `$postid = get_the_ID();` Here we get the post id to be able to filter the query. `$query1c = "SELECT....` Here we put the query, which selects the fields we want, filtered by `wp_term_taxonomy.taxonomy = 'productcategory'` and `wp_posts.ID =$postid` (this is where we use the `$postid` from before) and ordered by `wp_terms.name ASC`. `$categories = $wpdb->get_results( $query1c )` This runs the query, and saves the raw data to `$categories`. Now we need to convert the raw data into something we can use, the raw data is currently saved as `$categories` but we need each result individually so we put: `foreach ( $categories as $category)` Here one result gets known as `$category` `array_push( $catresult, "<a href='".$category->Url."'>".$category->Category."</a>" )` Here we 'push' each result individually to the array we created earlier - `$catresult`. Each result has been prepared with its link (`<a>` tag). One last thing - as we want these categories in a list, it would look better if they where separated by commas! So: `echo implode(', ', $catresult)` So here we 'implode' the array, which means we put something between each result of the array, which in this case is a comma followed by a space. This is then printed to the page by using the `echo` command. Finally `?>` tells the server to close this `php` section.
224,759
<p>I want to use post types to style video posts differently. This should be quite easily achieved with custom post types. </p> <p>But I only want the video post type to affect the post when it is in "single". </p> <p>In other words I want the front page to stay as it is but when a video post is clicked on (and single.php is rendered) I want it to be styled differently than regular posts.</p> <p>How can I achieve this? </p> <p>I have read a dozen articles about custom post types, but all of them explain how to render CPT on the front page, which is not what I need. </p> <p>Functions.php</p> <pre><code>add_theme_support( 'post-formats', array( 'aside', 'gallery', 'image', 'link', 'video', 'quote', 'link', 'video', 'status', 'audio', 'chat' ) ); </code></pre> <p>I am using _s for theme development so inside the theme root folder I have a folder called template-parts with content-none.php content-page.php content-search.php content-single.php content.php and <strong>single-video.php</strong></p>
[ { "answer_id": 224768, "author": "Victor", "author_id": 92972, "author_profile": "https://wordpress.stackexchange.com/users/92972", "pm_score": 0, "selected": false, "text": "<p>If you created the taxonomy yourself, you could set your own slug for the custom taxonomy. For Example:</p>\n\n<pre><code>register_taxonomy(\n 'productcategory',\n array(\n 'productpopups',\n ),\n array(\n 'labels' =&gt; array(\n 'name' =&gt; __('Categories', 'text-domain'),\n ),\n\n // --- set taxonomy slug ---\n 'rewrite' =&gt; array(\n 'slug' =&gt; '%productcategory%', // set taxonomy slug\n 'with_front' =&gt; false, // set this to false\n )\n // -------------------------\n )\n);\n\nflush_rewrite_rules(); // &lt;-- don't forget to add this line of code!\n</code></pre>\n" }, { "answer_id": 225191, "author": "CalvT", "author_id": 56659, "author_profile": "https://wordpress.stackexchange.com/users/56659", "pm_score": 1, "selected": true, "text": "<p>The code that I finally came up with to fix the problem!</p>\n\n<pre><code>&lt;?php\nglobal $wpdb;\n$catresult = array();\n$postid = get_the_ID();\n$query1c = \"SELECT wp_posts.ID, wp_terms.`name` AS `Category`, wp_pods_productcategory.`pc-url` AS `Url`\nFROM wp_posts\nINNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id\nINNER JOIN wp_terms ON wp_term_relationships.term_taxonomy_id = wp_terms.term_id\nLEFT OUTER JOIN wp_pods_productcategory ON wp_pods_productcategory.id = wp_term_relationships.term_taxonomy_id\nINNER JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_id\nWHERE wp_term_taxonomy.taxonomy = 'productcategory' AND wp_posts.ID =$postid\nORDER BY wp_terms.`name` ASC\";\n$categories = $wpdb-&gt;get_results( $query1c );\nforeach ( $categories as $category )\n{\narray_push( $catresult, \"&lt;a href='\".$category-&gt;Url.\"'&gt;\".$category-&gt;Category.\"&lt;/a&gt;\" );\n}\necho implode(', ', $catresult);\n?&gt;\n</code></pre>\n\n<p>So how does this work?</p>\n\n<p><code>&lt;?php</code> This is the opening tag so the server knows what comes next is <code>php</code>.</p>\n\n<p><code>global $wpdb</code> Here we tell the server that we'll be connecting to the WordPress Database.</p>\n\n<p><code>$catresult = array();</code> Here we create the array we'll use to store the data.</p>\n\n<p><code>$postid = get_the_ID();</code> Here we get the post id to be able to filter the query.</p>\n\n<p><code>$query1c = \"SELECT....</code> Here we put the query, which selects the fields we want, filtered by <code>wp_term_taxonomy.taxonomy = 'productcategory'</code> and <code>wp_posts.ID =$postid</code> (this is where we use the <code>$postid</code> from before) and ordered by <code>wp_terms.name ASC</code>.</p>\n\n<p><code>$categories = $wpdb-&gt;get_results( $query1c )</code> This runs the query, and saves the raw data to <code>$categories</code>.</p>\n\n<p>Now we need to convert the raw data into something we can use, the raw data is currently saved as <code>$categories</code> but we need each result individually so we put:</p>\n\n<p><code>foreach ( $categories as $category)</code> Here one result gets known as <code>$category</code></p>\n\n<p><code>array_push( $catresult, \"&lt;a href='\".$category-&gt;Url.\"'&gt;\".$category-&gt;Category.\"&lt;/a&gt;\" )</code> Here we 'push' each result individually to the array we created earlier - <code>$catresult</code>. Each result has been prepared with its link (<code>&lt;a&gt;</code> tag).</p>\n\n<p>One last thing - as we want these categories in a list, it would look better if they where separated by commas! So:</p>\n\n<p><code>echo implode(', ', $catresult)</code> So here we 'implode' the array, which means we put something between each result of the array, which in this case is a comma followed by a space. This is then printed to the page by using the <code>echo</code> command.</p>\n\n<p>Finally <code>?&gt;</code> tells the server to close this <code>php</code> section.</p>\n" }, { "answer_id": 284088, "author": "omukiguy", "author_id": 102683, "author_profile": "https://wordpress.stackexchange.com/users/102683", "pm_score": 2, "selected": false, "text": "<p>Sorry to come to the party late. Here is my solution</p>\n\n<pre><code>&lt;?php\n //Retrieve the terms in productcategory taxonomy with posts (not empty)\n $terms = get_terms( array ( 'taxonomy' =&gt; 'productcategory', 'hide_empty' =&gt; false, 'parent' =&gt; 0, 'orderby' =&gt; 'description', 'order' =&gt; 'ASC' ));\n\n //loop through each term to get its attributes\n foreach ($terms as $term) {\n\n //Uncomment below code to see all the available attributes.\n //var_dump($term); \n //die();\n $name = $term-&gt;name;\n\n //PHP -&gt; Store the link in variable to reuse\n //to get the link for the the particular term; you need to have the slug and pass it into the get_term_link() function.\n //the second argument is the taxonomy name in this case productcategory.\n $cat_link = get_term_link( $term-&gt;slug, 'productcategory' );\n\n?&gt;\n\n&lt;a href=\"&lt;?php echo $cat_link; ?&gt;\"&gt;&lt;?php echo $name; ?&gt;&lt;/a&gt;\n\n&lt;?php\n }\n\n?&gt;\n</code></pre>\n" } ]
2016/04/25
[ "https://wordpress.stackexchange.com/questions/224759", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82313/" ]
I want to use post types to style video posts differently. This should be quite easily achieved with custom post types. But I only want the video post type to affect the post when it is in "single". In other words I want the front page to stay as it is but when a video post is clicked on (and single.php is rendered) I want it to be styled differently than regular posts. How can I achieve this? I have read a dozen articles about custom post types, but all of them explain how to render CPT on the front page, which is not what I need. Functions.php ``` add_theme_support( 'post-formats', array( 'aside', 'gallery', 'image', 'link', 'video', 'quote', 'link', 'video', 'status', 'audio', 'chat' ) ); ``` I am using \_s for theme development so inside the theme root folder I have a folder called template-parts with content-none.php content-page.php content-search.php content-single.php content.php and **single-video.php**
The code that I finally came up with to fix the problem! ``` <?php global $wpdb; $catresult = array(); $postid = get_the_ID(); $query1c = "SELECT wp_posts.ID, wp_terms.`name` AS `Category`, wp_pods_productcategory.`pc-url` AS `Url` FROM wp_posts INNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id INNER JOIN wp_terms ON wp_term_relationships.term_taxonomy_id = wp_terms.term_id LEFT OUTER JOIN wp_pods_productcategory ON wp_pods_productcategory.id = wp_term_relationships.term_taxonomy_id INNER JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_id WHERE wp_term_taxonomy.taxonomy = 'productcategory' AND wp_posts.ID =$postid ORDER BY wp_terms.`name` ASC"; $categories = $wpdb->get_results( $query1c ); foreach ( $categories as $category ) { array_push( $catresult, "<a href='".$category->Url."'>".$category->Category."</a>" ); } echo implode(', ', $catresult); ?> ``` So how does this work? `<?php` This is the opening tag so the server knows what comes next is `php`. `global $wpdb` Here we tell the server that we'll be connecting to the WordPress Database. `$catresult = array();` Here we create the array we'll use to store the data. `$postid = get_the_ID();` Here we get the post id to be able to filter the query. `$query1c = "SELECT....` Here we put the query, which selects the fields we want, filtered by `wp_term_taxonomy.taxonomy = 'productcategory'` and `wp_posts.ID =$postid` (this is where we use the `$postid` from before) and ordered by `wp_terms.name ASC`. `$categories = $wpdb->get_results( $query1c )` This runs the query, and saves the raw data to `$categories`. Now we need to convert the raw data into something we can use, the raw data is currently saved as `$categories` but we need each result individually so we put: `foreach ( $categories as $category)` Here one result gets known as `$category` `array_push( $catresult, "<a href='".$category->Url."'>".$category->Category."</a>" )` Here we 'push' each result individually to the array we created earlier - `$catresult`. Each result has been prepared with its link (`<a>` tag). One last thing - as we want these categories in a list, it would look better if they where separated by commas! So: `echo implode(', ', $catresult)` So here we 'implode' the array, which means we put something between each result of the array, which in this case is a comma followed by a space. This is then printed to the page by using the `echo` command. Finally `?>` tells the server to close this `php` section.
224,783
<p>I was trying to add a content filter and i discovered that the filter was being called 3 times in total. I tried slowly deleting all of the plugins and eventually found that it was Yoast that was causing this. This is absolutely insane. This means that ever single content filter gets called 3 times every single time? The performance issues alone are seriously bad. Any idea what is causing this to happen. Surely this plugin would not be released if it was calling the content 2 times. </p> <p>For example. This hook will display one in the content (it does this without the plugin installed) and 2 more times at the top of the page when Yoast SEO is installed.</p> <pre><code>add_action( 'the_content', 'outputsomething'); function outputsomething() { echo "test"; } </code></pre>
[ { "answer_id": 224786, "author": "Z. Zlatev", "author_id": 4192, "author_profile": "https://wordpress.stackexchange.com/users/4192", "pm_score": 1, "selected": false, "text": "<p>Not sure what your question exactly is but yeah - for every <code>apply_filters( 'the_content', '...' );</code> all hooked filters will be executed. I wouldn't care that much how many times this happens but instead what content is being filtered each time - more the content bigger the performance penalty.</p>\n" }, { "answer_id": 244002, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>The core of your problem is that <code>the_content</code> is a filter not an action, and it is supposed to return values, not echo them.</p>\n\n<p>As for the \"called number of times\" part of the question, yes any hook can be called unlimited number of time. If you find that you need to return one result on the first call and different on the others it is a sign that you are doing something wrong or extremely hacky.</p>\n" }, { "answer_id": 244029, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>I'm afraid I cannot reproduce this problem. Running WP 4.6.1 and Yoast 3.7.1. I added the following to the functions file of my test install:</p>\n\n<pre><code>add_action( 'the_content', 'wpse224783_action');\nfunction wpse224783_action() \n { echo \"test123\"; }\n\nadd_filter( 'the_content', 'wpse224783_filter');\nfunction wpse224783_filter($content) \n { echo \"test456\" ; return $content . \"test789\" }\n</code></pre>\n\n<p>This leads to all my contents outputting <code>test123test456test789</code>. So, my conclusion is that this behaviour is not triggered only by the combination of a fresh WP install and Yoast. I used a profiling plugin, which indicated the functions only running once for every call to <code>the_content</code>. Somewhere else, possibly in your theme, something is triggering <code>the_content</code> multiple times.</p>\n" } ]
2016/04/25
[ "https://wordpress.stackexchange.com/questions/224783", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/190834/" ]
I was trying to add a content filter and i discovered that the filter was being called 3 times in total. I tried slowly deleting all of the plugins and eventually found that it was Yoast that was causing this. This is absolutely insane. This means that ever single content filter gets called 3 times every single time? The performance issues alone are seriously bad. Any idea what is causing this to happen. Surely this plugin would not be released if it was calling the content 2 times. For example. This hook will display one in the content (it does this without the plugin installed) and 2 more times at the top of the page when Yoast SEO is installed. ``` add_action( 'the_content', 'outputsomething'); function outputsomething() { echo "test"; } ```
The core of your problem is that `the_content` is a filter not an action, and it is supposed to return values, not echo them. As for the "called number of times" part of the question, yes any hook can be called unlimited number of time. If you find that you need to return one result on the first call and different on the others it is a sign that you are doing something wrong or extremely hacky.
224,800
<p>I'm trying to push a shortcode parameter value to a template file but for some reason I can't get the array value that I'm targeting into a single variable. Here is my code and the shortcode I'm using:</p> <pre><code>function content_table($atts) { $atts = shortcode_atts(array( 'tablepageid' =&gt; '' ), $atts); include(locate_template('table-layout.php')); } add_shortcode('ContentTable', 'content_table'); </code></pre> <p><strong>Edit</strong> I removed the quotes from my shortcode and I'm now able to see the value: [ContentTable tablepageid=4799]</p> <p>I created a page to test the shortcode function:</p> <pre><code>print_r(array_values($atts)); Array ( [0] =&gt; 4799 ) </code></pre> <p>The value from the shortcode is available but I'm having some trouble getting the value into a variable for my template to use:</p> <pre><code>$arr = $atts[0]; </code></pre> <p>The $arrTable variable is empty...I can't figure out why it's not 4799.</p>
[ { "answer_id": 224840, "author": "Z. Zlatev", "author_id": 4192, "author_profile": "https://wordpress.stackexchange.com/users/4192", "pm_score": 2, "selected": true, "text": "<p>You are probably confused by the output of <code>array_values()</code> which will always get you only array values without keys while <code>$atts</code> variable is actually an associative array.</p>\n\n<p>To extract your attribute use <code>$arr = $atts['tablepageid'];</code></p>\n\n<p>Cheers</p>\n" }, { "answer_id": 224844, "author": "Nathan Powell", "author_id": 27196, "author_profile": "https://wordpress.stackexchange.com/users/27196", "pm_score": -1, "selected": false, "text": "<p>Shortcodes are intended to <code>return</code> values, or <code>echo</code> them. You can use the <code>include</code> to the file you have, but unless you serve the intended <code>$atts</code> to the function there you won't see anything.</p>\n\n<p>Basically no one can help you unless we see the rest of your code. My best guess is that you need to declare the variable globally from the attributes in the shortcode and then claim it the template. </p>\n\n<p>Doing the above is just shy of the sillyness that is creating a function that accepts the attribute as a parameter to pass to the file that redeclares that functions' return value as a local variable.</p>\n\n<p>The list goes on in PHP. If you show your include file it would help.</p>\n" } ]
2016/04/25
[ "https://wordpress.stackexchange.com/questions/224800", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64789/" ]
I'm trying to push a shortcode parameter value to a template file but for some reason I can't get the array value that I'm targeting into a single variable. Here is my code and the shortcode I'm using: ``` function content_table($atts) { $atts = shortcode_atts(array( 'tablepageid' => '' ), $atts); include(locate_template('table-layout.php')); } add_shortcode('ContentTable', 'content_table'); ``` **Edit** I removed the quotes from my shortcode and I'm now able to see the value: [ContentTable tablepageid=4799] I created a page to test the shortcode function: ``` print_r(array_values($atts)); Array ( [0] => 4799 ) ``` The value from the shortcode is available but I'm having some trouble getting the value into a variable for my template to use: ``` $arr = $atts[0]; ``` The $arrTable variable is empty...I can't figure out why it's not 4799.
You are probably confused by the output of `array_values()` which will always get you only array values without keys while `$atts` variable is actually an associative array. To extract your attribute use `$arr = $atts['tablepageid'];` Cheers
224,808
<p>What would be the right way of using variable with same data in two functions? Is next approach good practice? I have a few of these variables set up in functions.php</p> <pre><code> $a = array('asdf', 'asdf', 'asdfasd'); add_filter( 'query_vars', 'themeslug_query_vars' , 10, 1 ); function themeslug_query_vars( $qvars ) { global $a; ... } add_action('pre_get_posts', 'search_pre_get_posts'); function search_pre_get_posts($query){ global $a; } </code></pre>
[ { "answer_id": 224810, "author": "Caspar", "author_id": 27191, "author_profile": "https://wordpress.stackexchange.com/users/27191", "pm_score": 3, "selected": true, "text": "<p>As a matter of good coding practice, global variables are problematic at best, dangerous at worst. They should be avoided if at all possible. Why? Because what if some other plugin developer also decides to define<code>$a</code> as a global? Whatever that plugin is doing will now overwrite your global <code>$a</code> and yours has the potential to wreak havoc with theirs.</p>\n\n<p>WordPress sets a bad precedent by using so many of them within its own code, but the good news is that you don't have to, and in most cases you can avoid adding to the mess of them that are already there.</p>\n\n<p>One easy way to avoid a global is to wrap the variable in another function that will return a value:</p>\n\n<pre><code>function my_theme_array() {\n return array('asdf', 'asdf', 'asdfasd');\n}\n</code></pre>\n\n<p>This would allow you to retrieve it from within other functions while keeping it in local scope and out of conflict with other code:</p>\n\n<pre><code>function themeslug_query_vars( $qvars ) {\n $a = my_theme_array(); \n ... // Now use $a for whatever.\n}\n\nfunction search_pre_get_posts($query){\n $a = my_theme_array();\n}\n</code></pre>\n\n<p>If you want to be able to change the contents that the function returns rather than having your array hard-coded into the <code>my_theme_array()</code> function, you could set up the function to take parameters that would change the currently set values of the array:</p>\n\n<pre><code>function my_theme_array_ver_2( array $new_values = null ) {\n static $my_array = array('asdf', 'asdf', 'asdfasd'); // default values\n if ( isset( $new_values ) ) {\n $my_array = $new_values;\n } else {\n return $my_array;\n }\n</code></pre>\n\n<p>So now you can call the function to set it's return value:</p>\n\n<pre><code>my_theme_array_ver_2( array( 1, 2, 3 ) );\n</code></pre>\n\n<p>or you can simply ask it to return whatever value is currently set:</p>\n\n<pre><code>$a_this_time_around = my_theme_array_ver_2();\n</code></pre>\n" }, { "answer_id": 224819, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 1, "selected": false, "text": "<p>Your array is a <strong>state</strong>, your functions are <strong>behavior</strong>. The standard way of combining state and behavior is an <strong>object</strong>. That's exactly what objects are made for.</p>\n\n<p>Create a class, pass the array to its constructor, and assign its public methods as callbacks to the hooks. This way, you keep everything nicely encapsulated, readable and testable. And maybe you can reuse the class in other projects.</p>\n\n<p>Example:</p>\n\n<pre><code>namespace WPSE;\n\nclass QueryVars\n{\n private $vars;\n\n public function __construct( array $vars )\n {\n $this-&gt;vars = $vars;\n }\n\n public function add_query_vars( array $wp_vars )\n {\n foreach ( $this-&gt;vars as $key =&gt; $value )\n $wp_vars[ $key ] = $value;\n\n return $wp_vars;\n }\n\n public function pre_get_posts( \\WP_Query $query )\n {\n foreach ( $this-&gt;vars as $key =&gt; $value )\n {\n if ( $query-&gt;get( $key ) )\n {\n // do something\n }\n }\n }\n}\n</code></pre>\n\n<p>And then register the callbacks:</p>\n\n<pre><code>$my_query_vars = new \\WPSE\\QueryVars(\n [\n 'hello' =&gt; 'world',\n 'foo' =&gt; 'bar',\n ]\n);\nadd_filter( 'query_vars', [ $my_query_vars, 'add_query_vars' ] );\nadd_action('pre_get_posts', [ $my_query_vars, 'pre_get_posts' ] );\n</code></pre>\n" } ]
2016/04/25
[ "https://wordpress.stackexchange.com/questions/224808", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85304/" ]
What would be the right way of using variable with same data in two functions? Is next approach good practice? I have a few of these variables set up in functions.php ``` $a = array('asdf', 'asdf', 'asdfasd'); add_filter( 'query_vars', 'themeslug_query_vars' , 10, 1 ); function themeslug_query_vars( $qvars ) { global $a; ... } add_action('pre_get_posts', 'search_pre_get_posts'); function search_pre_get_posts($query){ global $a; } ```
As a matter of good coding practice, global variables are problematic at best, dangerous at worst. They should be avoided if at all possible. Why? Because what if some other plugin developer also decides to define`$a` as a global? Whatever that plugin is doing will now overwrite your global `$a` and yours has the potential to wreak havoc with theirs. WordPress sets a bad precedent by using so many of them within its own code, but the good news is that you don't have to, and in most cases you can avoid adding to the mess of them that are already there. One easy way to avoid a global is to wrap the variable in another function that will return a value: ``` function my_theme_array() { return array('asdf', 'asdf', 'asdfasd'); } ``` This would allow you to retrieve it from within other functions while keeping it in local scope and out of conflict with other code: ``` function themeslug_query_vars( $qvars ) { $a = my_theme_array(); ... // Now use $a for whatever. } function search_pre_get_posts($query){ $a = my_theme_array(); } ``` If you want to be able to change the contents that the function returns rather than having your array hard-coded into the `my_theme_array()` function, you could set up the function to take parameters that would change the currently set values of the array: ``` function my_theme_array_ver_2( array $new_values = null ) { static $my_array = array('asdf', 'asdf', 'asdfasd'); // default values if ( isset( $new_values ) ) { $my_array = $new_values; } else { return $my_array; } ``` So now you can call the function to set it's return value: ``` my_theme_array_ver_2( array( 1, 2, 3 ) ); ``` or you can simply ask it to return whatever value is currently set: ``` $a_this_time_around = my_theme_array_ver_2(); ```
224,816
<p>So I've been tinkering with the admin roles and I can't seem to be able to revoke create page rights for the admin. I can only find 'Edit page'.</p> <p>If I remove Edit page, the entire pages tab goes away(probably because of not enough rights)..</p> <p>Is there a way to disable creating/deleting pages and keep the pages tab?</p> <p>I have this so far.</p> <pre><code>$role = get_role('administrator'); $role-&gt;remove_cap('delete_pages'); $role-&gt;remove_cap('delete_others_pages'); $role-&gt;remove_cap('delete_published_pages'); $role-&gt;remove_cap('publish_pages'); </code></pre>
[ { "answer_id": 224810, "author": "Caspar", "author_id": 27191, "author_profile": "https://wordpress.stackexchange.com/users/27191", "pm_score": 3, "selected": true, "text": "<p>As a matter of good coding practice, global variables are problematic at best, dangerous at worst. They should be avoided if at all possible. Why? Because what if some other plugin developer also decides to define<code>$a</code> as a global? Whatever that plugin is doing will now overwrite your global <code>$a</code> and yours has the potential to wreak havoc with theirs.</p>\n\n<p>WordPress sets a bad precedent by using so many of them within its own code, but the good news is that you don't have to, and in most cases you can avoid adding to the mess of them that are already there.</p>\n\n<p>One easy way to avoid a global is to wrap the variable in another function that will return a value:</p>\n\n<pre><code>function my_theme_array() {\n return array('asdf', 'asdf', 'asdfasd');\n}\n</code></pre>\n\n<p>This would allow you to retrieve it from within other functions while keeping it in local scope and out of conflict with other code:</p>\n\n<pre><code>function themeslug_query_vars( $qvars ) {\n $a = my_theme_array(); \n ... // Now use $a for whatever.\n}\n\nfunction search_pre_get_posts($query){\n $a = my_theme_array();\n}\n</code></pre>\n\n<p>If you want to be able to change the contents that the function returns rather than having your array hard-coded into the <code>my_theme_array()</code> function, you could set up the function to take parameters that would change the currently set values of the array:</p>\n\n<pre><code>function my_theme_array_ver_2( array $new_values = null ) {\n static $my_array = array('asdf', 'asdf', 'asdfasd'); // default values\n if ( isset( $new_values ) ) {\n $my_array = $new_values;\n } else {\n return $my_array;\n }\n</code></pre>\n\n<p>So now you can call the function to set it's return value:</p>\n\n<pre><code>my_theme_array_ver_2( array( 1, 2, 3 ) );\n</code></pre>\n\n<p>or you can simply ask it to return whatever value is currently set:</p>\n\n<pre><code>$a_this_time_around = my_theme_array_ver_2();\n</code></pre>\n" }, { "answer_id": 224819, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 1, "selected": false, "text": "<p>Your array is a <strong>state</strong>, your functions are <strong>behavior</strong>. The standard way of combining state and behavior is an <strong>object</strong>. That's exactly what objects are made for.</p>\n\n<p>Create a class, pass the array to its constructor, and assign its public methods as callbacks to the hooks. This way, you keep everything nicely encapsulated, readable and testable. And maybe you can reuse the class in other projects.</p>\n\n<p>Example:</p>\n\n<pre><code>namespace WPSE;\n\nclass QueryVars\n{\n private $vars;\n\n public function __construct( array $vars )\n {\n $this-&gt;vars = $vars;\n }\n\n public function add_query_vars( array $wp_vars )\n {\n foreach ( $this-&gt;vars as $key =&gt; $value )\n $wp_vars[ $key ] = $value;\n\n return $wp_vars;\n }\n\n public function pre_get_posts( \\WP_Query $query )\n {\n foreach ( $this-&gt;vars as $key =&gt; $value )\n {\n if ( $query-&gt;get( $key ) )\n {\n // do something\n }\n }\n }\n}\n</code></pre>\n\n<p>And then register the callbacks:</p>\n\n<pre><code>$my_query_vars = new \\WPSE\\QueryVars(\n [\n 'hello' =&gt; 'world',\n 'foo' =&gt; 'bar',\n ]\n);\nadd_filter( 'query_vars', [ $my_query_vars, 'add_query_vars' ] );\nadd_action('pre_get_posts', [ $my_query_vars, 'pre_get_posts' ] );\n</code></pre>\n" } ]
2016/04/25
[ "https://wordpress.stackexchange.com/questions/224816", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91852/" ]
So I've been tinkering with the admin roles and I can't seem to be able to revoke create page rights for the admin. I can only find 'Edit page'. If I remove Edit page, the entire pages tab goes away(probably because of not enough rights).. Is there a way to disable creating/deleting pages and keep the pages tab? I have this so far. ``` $role = get_role('administrator'); $role->remove_cap('delete_pages'); $role->remove_cap('delete_others_pages'); $role->remove_cap('delete_published_pages'); $role->remove_cap('publish_pages'); ```
As a matter of good coding practice, global variables are problematic at best, dangerous at worst. They should be avoided if at all possible. Why? Because what if some other plugin developer also decides to define`$a` as a global? Whatever that plugin is doing will now overwrite your global `$a` and yours has the potential to wreak havoc with theirs. WordPress sets a bad precedent by using so many of them within its own code, but the good news is that you don't have to, and in most cases you can avoid adding to the mess of them that are already there. One easy way to avoid a global is to wrap the variable in another function that will return a value: ``` function my_theme_array() { return array('asdf', 'asdf', 'asdfasd'); } ``` This would allow you to retrieve it from within other functions while keeping it in local scope and out of conflict with other code: ``` function themeslug_query_vars( $qvars ) { $a = my_theme_array(); ... // Now use $a for whatever. } function search_pre_get_posts($query){ $a = my_theme_array(); } ``` If you want to be able to change the contents that the function returns rather than having your array hard-coded into the `my_theme_array()` function, you could set up the function to take parameters that would change the currently set values of the array: ``` function my_theme_array_ver_2( array $new_values = null ) { static $my_array = array('asdf', 'asdf', 'asdfasd'); // default values if ( isset( $new_values ) ) { $my_array = $new_values; } else { return $my_array; } ``` So now you can call the function to set it's return value: ``` my_theme_array_ver_2( array( 1, 2, 3 ) ); ``` or you can simply ask it to return whatever value is currently set: ``` $a_this_time_around = my_theme_array_ver_2(); ```
224,817
<p>I am trying to modify my loop to save post data by category. I found some code on this site that saved the post's titles based on their categories and tried to modify this to save the post's content. However, while <code>get_the_title</code> and <code>get_the_category</code> work, <code>get_the_content</code> returns null.</p> <p>Here is the code:</p> <pre><code>if ( false === ( $q = get_transient( 'category_list' ) ) ) { $args = array( 'posts_per_page' =&gt; -1 ); $query = new WP_Query($args); $q = array(); $body = array(); while ( $query-&gt;have_posts() ) { $query-&gt;the_post(); $a = '&lt;a href="'. get_permalink() .'"&gt;' . get_the_title() .'&lt;/a&gt;'; $post_id = get_the_ID(); $post_id = $post-&gt;ID; $body[$post_id] = array(); $body[$post_id]['title'] = '&lt;a href="'. get_permalink() .'"&gt;' . get_the_title() .'&lt;/a&gt;'; //works $body[$post_id]['content'] = get_the_content('Read more'); $categories = get_the_category(); foreach ( $categories as $key=&gt;$category ) { $b = '&lt;a href="' . get_category_link( $category ) . '"&gt;' . $category-&gt;name . '&lt;/a&gt;'; } $q[$b][] = $post_id; // Create an array with the category names and post titles } /* Restore original Post Data */ wp_reset_postdata(); set_transient( 'category_list', $q, 12 * HOUR_IN_SECONDS ); } </code></pre> <p>Edit: Here is how I am using the <code>$body</code> array:</p> <pre><code>foreach($q[$b] as $post) { echo('&lt;div class="teaser"&gt;&lt;div class="teaser-title"&gt;&lt;a href = ""&gt;' . $post . '&lt;/a&gt;&lt;/div&gt;&lt;div class="teaser-text"&gt;'. $body[$post] . '&lt;/div&gt;&lt;div class="teaser-footer"&gt;&lt;p&gt;pemsource.org&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;'); } </code></pre> <p>Edit2: I added the full code. When I do a var dump of body I get NULL and when I do a var dump of $q I get </p> <pre><code>array(3) { ["Conundrums"]=&gt; array(1) { [0]=&gt; string(64) "new post" } ["Tips and Tricks"]=&gt; array(1) { [0]=&gt; string(80) "Tips and tricks" } ["Uncategorized"]=&gt; array(1) { [0]=&gt; string(78) "Tips and Tricks" } } </code></pre> <p>seemingly regardless of how I edit the loop. I am very confused. Any help is much appreciated</p>
[ { "answer_id": 224860, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 2, "selected": false, "text": "<p><code>echo $post-&gt;post_content;</code> will echo your post content. Keep in mind though, it's raw out of the database (same as <code>get_the_content()</code>). If you want to apply the same filters that <code>the_content()</code> receives, follow the instructions in the <a href=\"https://developer.wordpress.org/reference/functions/the_content/#Alternative_Usage\" rel=\"nofollow\">codex</a>:</p>\n\n<pre><code>&lt;?php\n$content = apply_filters('the_content', $content);\n$content = str_replace(']]&gt;', ']]&gt;', $content);\n?&gt;\n</code></pre>\n" }, { "answer_id": 224862, "author": "Anish Rai", "author_id": 78683, "author_profile": "https://wordpress.stackexchange.com/users/78683", "pm_score": -1, "selected": false, "text": "<p>maybe try <code>&lt;?php</code> instead of <code>&lt;?</code> in your lines of code, not sure but I understand that this can cause problems.</p>\n\n<p>or use <code>&lt;?php echo $post-&gt;post_content; ?&gt;</code>\nand try without 'Read More' means only <code>&lt;?php the_content(); ?&gt;</code></p>\n" } ]
2016/04/25
[ "https://wordpress.stackexchange.com/questions/224817", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92721/" ]
I am trying to modify my loop to save post data by category. I found some code on this site that saved the post's titles based on their categories and tried to modify this to save the post's content. However, while `get_the_title` and `get_the_category` work, `get_the_content` returns null. Here is the code: ``` if ( false === ( $q = get_transient( 'category_list' ) ) ) { $args = array( 'posts_per_page' => -1 ); $query = new WP_Query($args); $q = array(); $body = array(); while ( $query->have_posts() ) { $query->the_post(); $a = '<a href="'. get_permalink() .'">' . get_the_title() .'</a>'; $post_id = get_the_ID(); $post_id = $post->ID; $body[$post_id] = array(); $body[$post_id]['title'] = '<a href="'. get_permalink() .'">' . get_the_title() .'</a>'; //works $body[$post_id]['content'] = get_the_content('Read more'); $categories = get_the_category(); foreach ( $categories as $key=>$category ) { $b = '<a href="' . get_category_link( $category ) . '">' . $category->name . '</a>'; } $q[$b][] = $post_id; // Create an array with the category names and post titles } /* Restore original Post Data */ wp_reset_postdata(); set_transient( 'category_list', $q, 12 * HOUR_IN_SECONDS ); } ``` Edit: Here is how I am using the `$body` array: ``` foreach($q[$b] as $post) { echo('<div class="teaser"><div class="teaser-title"><a href = "">' . $post . '</a></div><div class="teaser-text">'. $body[$post] . '</div><div class="teaser-footer"><p>pemsource.org</p></div></div>'); } ``` Edit2: I added the full code. When I do a var dump of body I get NULL and when I do a var dump of $q I get ``` array(3) { ["Conundrums"]=> array(1) { [0]=> string(64) "new post" } ["Tips and Tricks"]=> array(1) { [0]=> string(80) "Tips and tricks" } ["Uncategorized"]=> array(1) { [0]=> string(78) "Tips and Tricks" } } ``` seemingly regardless of how I edit the loop. I am very confused. Any help is much appreciated
`echo $post->post_content;` will echo your post content. Keep in mind though, it's raw out of the database (same as `get_the_content()`). If you want to apply the same filters that `the_content()` receives, follow the instructions in the [codex](https://developer.wordpress.org/reference/functions/the_content/#Alternative_Usage): ``` <?php $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); ?> ```
224,945
<p>I'm a little bit confused with the use of the Loop. This is my first theme and i just use index.php currently to display all my pages. It works fine for pages but have_posts return false when i try to display a single post. Here is the code of the index.php:</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class="left"&gt; &lt;?php if ( have_posts() ) : // Start the loop. while ( have_posts() ) : the_post(); //echo for debugging echo 'index&lt;br&gt;'; echo get_the_ID().'&lt;br&gt;'; //function to display page field_page_builder_front_display(get_the_ID(),get_post_type(get_the_ID())); endwhile; else : ?&gt; Sorry, this page does not exist &lt;?php endif; ?&gt; &lt;/div&gt; &lt;?php //display custom sidebar get_side_bar(); get_footer(); ?&gt; </code></pre> <p>This index.php return "Sorry, this does not exist" for all my single post (articles or custom post). I thought it was because the loop is only for displaying multiple posts but the file single.php of the theme twentfifteen use the loop too, so i don't understand the problem.</p> <p>Thank in advance for all your help !</p>
[ { "answer_id": 224956, "author": "Nabeel Khan", "author_id": 57389, "author_profile": "https://wordpress.stackexchange.com/users/57389", "pm_score": -1, "selected": false, "text": "<p>You don't have any posts query running probably.</p>\n\n<p>Try this (added <code>query_posts();</code>)</p>\n\n<pre><code>&lt;?php\nget_header();\n?&gt;\n&lt;div class=\"left\"&gt;\n &lt;?php \n query_posts( $args );\n if ( have_posts() ) :\n // Start the loop.\n while ( have_posts() ) : the_post();\n //echo for debugging\n echo 'index&lt;br&gt;';\n echo get_the_ID().'&lt;br&gt;';\n //function to display page\n field_page_builder_front_display(get_the_ID(),get_post_type(get_the_ID()));\n endwhile;\n else :\n ?&gt; \n Sorry, this page does not exist\n &lt;?php\n endif;\n ?&gt;\n&lt;/div&gt;\n&lt;?php\n//display custom sidebar\nget_side_bar();\nget_footer();\n?&gt;\n</code></pre>\n" }, { "answer_id": 382813, "author": "JoeMoe1984", "author_id": 32601, "author_profile": "https://wordpress.stackexchange.com/users/32601", "pm_score": 0, "selected": false, "text": "<p>Late answer but, one possible scenario this could be happening is if you register two custom post types with the same permalink slug.</p>\n<p>You can debug this by doing a <code>var_dump</code> of the global variable <code>$wp_query</code>.</p>\n<pre class=\"lang-php prettyprint-override\"><code>global $wp_query;\nvar_dump($wp_query);\n</code></pre>\n<p>Check to see if the <code>post_type</code> in the query matches the post type of the page you are currently visiting.</p>\n<p>If you find that it does not match then your next step is to check out the arguments where both the post types are being registered. Take a look at the <code>rewrite</code> specifically. If the <code>slug</code> is set to the same value, you will have a conflict between the two custom post types.</p>\n<p><strong>Bad</strong></p>\n<pre><code>// post type (a)\n$args_a = array(\n 'rewrite' =&gt; array(\n 'slug' =&gt; 'hello'\n ),\n);\n\n// post type (b)\n$args_b = array(\n 'rewrite' =&gt; array(\n 'slug' =&gt; 'hello'\n ),\n);\n</code></pre>\n<p><strong>Good</strong></p>\n<pre class=\"lang-php prettyprint-override\"><code>// post type (a)\n$args_a = array(\n 'rewrite' =&gt; array(\n 'slug' =&gt; 'hello'\n ),\n);\n\n// post type (b)\n$args_b = array(\n 'rewrite' =&gt; array(\n 'slug' =&gt; 'world' // &lt;-- this is now different.\n ),\n);\n</code></pre>\n<p>That alone may not fix your issue because you will need to flush the permalinks. To do that, you can just go to the Admin Dashboard &gt; Settings &gt; Permalinks page and click on the <code>save changes</code> button. That will flush the permalinks so they are now updated to be <code>hello</code> and <code>world</code> respectively for your custom post types.</p>\n" } ]
2016/04/27
[ "https://wordpress.stackexchange.com/questions/224945", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93085/" ]
I'm a little bit confused with the use of the Loop. This is my first theme and i just use index.php currently to display all my pages. It works fine for pages but have\_posts return false when i try to display a single post. Here is the code of the index.php: ``` <?php get_header(); ?> <div class="left"> <?php if ( have_posts() ) : // Start the loop. while ( have_posts() ) : the_post(); //echo for debugging echo 'index<br>'; echo get_the_ID().'<br>'; //function to display page field_page_builder_front_display(get_the_ID(),get_post_type(get_the_ID())); endwhile; else : ?> Sorry, this page does not exist <?php endif; ?> </div> <?php //display custom sidebar get_side_bar(); get_footer(); ?> ``` This index.php return "Sorry, this does not exist" for all my single post (articles or custom post). I thought it was because the loop is only for displaying multiple posts but the file single.php of the theme twentfifteen use the loop too, so i don't understand the problem. Thank in advance for all your help !
Late answer but, one possible scenario this could be happening is if you register two custom post types with the same permalink slug. You can debug this by doing a `var_dump` of the global variable `$wp_query`. ```php global $wp_query; var_dump($wp_query); ``` Check to see if the `post_type` in the query matches the post type of the page you are currently visiting. If you find that it does not match then your next step is to check out the arguments where both the post types are being registered. Take a look at the `rewrite` specifically. If the `slug` is set to the same value, you will have a conflict between the two custom post types. **Bad** ``` // post type (a) $args_a = array( 'rewrite' => array( 'slug' => 'hello' ), ); // post type (b) $args_b = array( 'rewrite' => array( 'slug' => 'hello' ), ); ``` **Good** ```php // post type (a) $args_a = array( 'rewrite' => array( 'slug' => 'hello' ), ); // post type (b) $args_b = array( 'rewrite' => array( 'slug' => 'world' // <-- this is now different. ), ); ``` That alone may not fix your issue because you will need to flush the permalinks. To do that, you can just go to the Admin Dashboard > Settings > Permalinks page and click on the `save changes` button. That will flush the permalinks so they are now updated to be `hello` and `world` respectively for your custom post types.
224,947
<p>How to browse other website without leaving domain?</p> <p>for ex. my website is websites1.com and i want to someone to goto website2.com but doamin name in address bar must be website1.com only.</p>
[ { "answer_id": 224956, "author": "Nabeel Khan", "author_id": 57389, "author_profile": "https://wordpress.stackexchange.com/users/57389", "pm_score": -1, "selected": false, "text": "<p>You don't have any posts query running probably.</p>\n\n<p>Try this (added <code>query_posts();</code>)</p>\n\n<pre><code>&lt;?php\nget_header();\n?&gt;\n&lt;div class=\"left\"&gt;\n &lt;?php \n query_posts( $args );\n if ( have_posts() ) :\n // Start the loop.\n while ( have_posts() ) : the_post();\n //echo for debugging\n echo 'index&lt;br&gt;';\n echo get_the_ID().'&lt;br&gt;';\n //function to display page\n field_page_builder_front_display(get_the_ID(),get_post_type(get_the_ID()));\n endwhile;\n else :\n ?&gt; \n Sorry, this page does not exist\n &lt;?php\n endif;\n ?&gt;\n&lt;/div&gt;\n&lt;?php\n//display custom sidebar\nget_side_bar();\nget_footer();\n?&gt;\n</code></pre>\n" }, { "answer_id": 382813, "author": "JoeMoe1984", "author_id": 32601, "author_profile": "https://wordpress.stackexchange.com/users/32601", "pm_score": 0, "selected": false, "text": "<p>Late answer but, one possible scenario this could be happening is if you register two custom post types with the same permalink slug.</p>\n<p>You can debug this by doing a <code>var_dump</code> of the global variable <code>$wp_query</code>.</p>\n<pre class=\"lang-php prettyprint-override\"><code>global $wp_query;\nvar_dump($wp_query);\n</code></pre>\n<p>Check to see if the <code>post_type</code> in the query matches the post type of the page you are currently visiting.</p>\n<p>If you find that it does not match then your next step is to check out the arguments where both the post types are being registered. Take a look at the <code>rewrite</code> specifically. If the <code>slug</code> is set to the same value, you will have a conflict between the two custom post types.</p>\n<p><strong>Bad</strong></p>\n<pre><code>// post type (a)\n$args_a = array(\n 'rewrite' =&gt; array(\n 'slug' =&gt; 'hello'\n ),\n);\n\n// post type (b)\n$args_b = array(\n 'rewrite' =&gt; array(\n 'slug' =&gt; 'hello'\n ),\n);\n</code></pre>\n<p><strong>Good</strong></p>\n<pre class=\"lang-php prettyprint-override\"><code>// post type (a)\n$args_a = array(\n 'rewrite' =&gt; array(\n 'slug' =&gt; 'hello'\n ),\n);\n\n// post type (b)\n$args_b = array(\n 'rewrite' =&gt; array(\n 'slug' =&gt; 'world' // &lt;-- this is now different.\n ),\n);\n</code></pre>\n<p>That alone may not fix your issue because you will need to flush the permalinks. To do that, you can just go to the Admin Dashboard &gt; Settings &gt; Permalinks page and click on the <code>save changes</code> button. That will flush the permalinks so they are now updated to be <code>hello</code> and <code>world</code> respectively for your custom post types.</p>\n" } ]
2016/04/27
[ "https://wordpress.stackexchange.com/questions/224947", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93087/" ]
How to browse other website without leaving domain? for ex. my website is websites1.com and i want to someone to goto website2.com but doamin name in address bar must be website1.com only.
Late answer but, one possible scenario this could be happening is if you register two custom post types with the same permalink slug. You can debug this by doing a `var_dump` of the global variable `$wp_query`. ```php global $wp_query; var_dump($wp_query); ``` Check to see if the `post_type` in the query matches the post type of the page you are currently visiting. If you find that it does not match then your next step is to check out the arguments where both the post types are being registered. Take a look at the `rewrite` specifically. If the `slug` is set to the same value, you will have a conflict between the two custom post types. **Bad** ``` // post type (a) $args_a = array( 'rewrite' => array( 'slug' => 'hello' ), ); // post type (b) $args_b = array( 'rewrite' => array( 'slug' => 'hello' ), ); ``` **Good** ```php // post type (a) $args_a = array( 'rewrite' => array( 'slug' => 'hello' ), ); // post type (b) $args_b = array( 'rewrite' => array( 'slug' => 'world' // <-- this is now different. ), ); ``` That alone may not fix your issue because you will need to flush the permalinks. To do that, you can just go to the Admin Dashboard > Settings > Permalinks page and click on the `save changes` button. That will flush the permalinks so they are now updated to be `hello` and `world` respectively for your custom post types.
224,964
<p>Why <code>do_shortcode</code> doesn't work in a REST call ?</p> <p>In the example below, <code>do_shortcode</code> exists, but the shortcode isn't interpreted.</p> <h2>Route declaration</h2> <pre><code>/* Adding a route with callback is interpret_shortcode function */ add_action( 'rest_api_init', function () { register_rest_route( 'test', '/someContent', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'interpret_shortcode' ) ); } ); </code></pre> <h2>Shortcode call</h2> <pre><code>function interpret_shortcode( $data ) { $content; if ( function_exists( 'do_shortcode' ) ) { $content = do_shortcode("[et_pb_text] abc [/et_pb_text]"); } else { $content = "do_shortcode is missing"; } return array('content'=&gt;$content); //Output "[et_pb_text] abc [/et_pb_text]" } </code></pre> <p>In a REST call, are we in the same situation as the one describe <a href="https://wordpress.stackexchange.com/questions/53309/why-might-a-plugins-do-shortcode-not-work-in-an-ajax-request">here</a> about Ajax request ?</p>
[ { "answer_id": 224972, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Availability of shortcodes defined by plugins at any point of the code is undefined expect for (and even that is a maybe) singular content.</p>\n\n<p>In most cases outside of that context you better call the function implementing it with the applicable parameters instead of \"parsing\" the shortcode.</p>\n" }, { "answer_id": 225222, "author": "Jordane CURE", "author_id": 92858, "author_profile": "https://wordpress.stackexchange.com/users/92858", "pm_score": 2, "selected": true, "text": "<h2>Solution</h2>\n\n<p>I find a workaround for this issue. I post it for posterity.</p>\n\n<p>This is an issue, several issue, between divi and REST Api. </p>\n\n<p>In the exemple bellow, <code>register_rest_field</code> is used instead of <code>register_rest_route</code>, but the fix is valid for both method.</p>\n\n<p>This solution could not be very futureproof. But, at least, their is no modification inside Divi Builder or Rest API. </p>\n\n<pre><code>/*\n Edit Rest call\n*/\nadd_action( 'rest_api_init', function ()\n{\n register_rest_field(\n 'page',\n 'content',\n array(\n 'get_callback' =&gt; 'duo_get_divi_content',\n 'update_callback' =&gt; null,\n 'schema' =&gt; null,\n )\n );\n});\n\nfunction duo_get_divi_content( $object, $field_name, $request )\n{\n //Set is_singular to true to ovoid \"read more issue\"\n //Issue come from is_singular () in divi-builder.php line 73\n global $wp_query;\n $wp_query-&gt;is_singular = true;\n\n\n //Set divi shortcode\n //The 2 function bellow are define in 'init' but they are call in 'wp'\n //REST Api exit after 'parse_request' hook, it's before 'wp' so divi's shortcode are not set\n et_builder_init_global_settings ();\n et_builder_add_main_elements ();\n\n\n //Define $post, if not defined, divi will not add outter_content and inner_content warper\n //Issue come from get_the_ID() in divi-builder.php line 69\n global $post;\n $post = get_post ($object['id']);\n\n //Apply the_content's filter, one of them interpret shortcodes\n $output = apply_filters( 'the_content', $post-&gt;post_content );\n\n return $output;\n}\n</code></pre>\n" } ]
2016/04/27
[ "https://wordpress.stackexchange.com/questions/224964", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92858/" ]
Why `do_shortcode` doesn't work in a REST call ? In the example below, `do_shortcode` exists, but the shortcode isn't interpreted. Route declaration ----------------- ``` /* Adding a route with callback is interpret_shortcode function */ add_action( 'rest_api_init', function () { register_rest_route( 'test', '/someContent', array( 'methods' => 'GET', 'callback' => 'interpret_shortcode' ) ); } ); ``` Shortcode call -------------- ``` function interpret_shortcode( $data ) { $content; if ( function_exists( 'do_shortcode' ) ) { $content = do_shortcode("[et_pb_text] abc [/et_pb_text]"); } else { $content = "do_shortcode is missing"; } return array('content'=>$content); //Output "[et_pb_text] abc [/et_pb_text]" } ``` In a REST call, are we in the same situation as the one describe [here](https://wordpress.stackexchange.com/questions/53309/why-might-a-plugins-do-shortcode-not-work-in-an-ajax-request) about Ajax request ?
Solution -------- I find a workaround for this issue. I post it for posterity. This is an issue, several issue, between divi and REST Api. In the exemple bellow, `register_rest_field` is used instead of `register_rest_route`, but the fix is valid for both method. This solution could not be very futureproof. But, at least, their is no modification inside Divi Builder or Rest API. ``` /* Edit Rest call */ add_action( 'rest_api_init', function () { register_rest_field( 'page', 'content', array( 'get_callback' => 'duo_get_divi_content', 'update_callback' => null, 'schema' => null, ) ); }); function duo_get_divi_content( $object, $field_name, $request ) { //Set is_singular to true to ovoid "read more issue" //Issue come from is_singular () in divi-builder.php line 73 global $wp_query; $wp_query->is_singular = true; //Set divi shortcode //The 2 function bellow are define in 'init' but they are call in 'wp' //REST Api exit after 'parse_request' hook, it's before 'wp' so divi's shortcode are not set et_builder_init_global_settings (); et_builder_add_main_elements (); //Define $post, if not defined, divi will not add outter_content and inner_content warper //Issue come from get_the_ID() in divi-builder.php line 69 global $post; $post = get_post ($object['id']); //Apply the_content's filter, one of them interpret shortcodes $output = apply_filters( 'the_content', $post->post_content ); return $output; } ```
224,976
<p>I hope I can find some help or advice here regarding custom taxonomies auto-complete (maybe there is a ready-plugin but I am not aware of it).</p> <p>I have custom taxonomy which have around 500 items. So when I admin user create new post and need to choose one or multiple item in add/edit post screen, he needs to scroll down and search through all of those items. It is a lot of time-consuming job.</p> <p>Is there any kind of auto-complete possibility that can be done for custom taxonomy, similar to tag auto-complete option?</p> <p>Thank you</p>
[ { "answer_id": 224972, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Availability of shortcodes defined by plugins at any point of the code is undefined expect for (and even that is a maybe) singular content.</p>\n\n<p>In most cases outside of that context you better call the function implementing it with the applicable parameters instead of \"parsing\" the shortcode.</p>\n" }, { "answer_id": 225222, "author": "Jordane CURE", "author_id": 92858, "author_profile": "https://wordpress.stackexchange.com/users/92858", "pm_score": 2, "selected": true, "text": "<h2>Solution</h2>\n\n<p>I find a workaround for this issue. I post it for posterity.</p>\n\n<p>This is an issue, several issue, between divi and REST Api. </p>\n\n<p>In the exemple bellow, <code>register_rest_field</code> is used instead of <code>register_rest_route</code>, but the fix is valid for both method.</p>\n\n<p>This solution could not be very futureproof. But, at least, their is no modification inside Divi Builder or Rest API. </p>\n\n<pre><code>/*\n Edit Rest call\n*/\nadd_action( 'rest_api_init', function ()\n{\n register_rest_field(\n 'page',\n 'content',\n array(\n 'get_callback' =&gt; 'duo_get_divi_content',\n 'update_callback' =&gt; null,\n 'schema' =&gt; null,\n )\n );\n});\n\nfunction duo_get_divi_content( $object, $field_name, $request )\n{\n //Set is_singular to true to ovoid \"read more issue\"\n //Issue come from is_singular () in divi-builder.php line 73\n global $wp_query;\n $wp_query-&gt;is_singular = true;\n\n\n //Set divi shortcode\n //The 2 function bellow are define in 'init' but they are call in 'wp'\n //REST Api exit after 'parse_request' hook, it's before 'wp' so divi's shortcode are not set\n et_builder_init_global_settings ();\n et_builder_add_main_elements ();\n\n\n //Define $post, if not defined, divi will not add outter_content and inner_content warper\n //Issue come from get_the_ID() in divi-builder.php line 69\n global $post;\n $post = get_post ($object['id']);\n\n //Apply the_content's filter, one of them interpret shortcodes\n $output = apply_filters( 'the_content', $post-&gt;post_content );\n\n return $output;\n}\n</code></pre>\n" } ]
2016/04/27
[ "https://wordpress.stackexchange.com/questions/224976", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31498/" ]
I hope I can find some help or advice here regarding custom taxonomies auto-complete (maybe there is a ready-plugin but I am not aware of it). I have custom taxonomy which have around 500 items. So when I admin user create new post and need to choose one or multiple item in add/edit post screen, he needs to scroll down and search through all of those items. It is a lot of time-consuming job. Is there any kind of auto-complete possibility that can be done for custom taxonomy, similar to tag auto-complete option? Thank you
Solution -------- I find a workaround for this issue. I post it for posterity. This is an issue, several issue, between divi and REST Api. In the exemple bellow, `register_rest_field` is used instead of `register_rest_route`, but the fix is valid for both method. This solution could not be very futureproof. But, at least, their is no modification inside Divi Builder or Rest API. ``` /* Edit Rest call */ add_action( 'rest_api_init', function () { register_rest_field( 'page', 'content', array( 'get_callback' => 'duo_get_divi_content', 'update_callback' => null, 'schema' => null, ) ); }); function duo_get_divi_content( $object, $field_name, $request ) { //Set is_singular to true to ovoid "read more issue" //Issue come from is_singular () in divi-builder.php line 73 global $wp_query; $wp_query->is_singular = true; //Set divi shortcode //The 2 function bellow are define in 'init' but they are call in 'wp' //REST Api exit after 'parse_request' hook, it's before 'wp' so divi's shortcode are not set et_builder_init_global_settings (); et_builder_add_main_elements (); //Define $post, if not defined, divi will not add outter_content and inner_content warper //Issue come from get_the_ID() in divi-builder.php line 69 global $post; $post = get_post ($object['id']); //Apply the_content's filter, one of them interpret shortcodes $output = apply_filters( 'the_content', $post->post_content ); return $output; } ```
224,984
<p>I'm trying to change the category for all posts of an author. I've been looking on here for about an hour and haven't found a solution.. </p> <p>Any help would be greatly appreciated :)</p> <p>Thanks, j03</p>
[ { "answer_id": 224972, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Availability of shortcodes defined by plugins at any point of the code is undefined expect for (and even that is a maybe) singular content.</p>\n\n<p>In most cases outside of that context you better call the function implementing it with the applicable parameters instead of \"parsing\" the shortcode.</p>\n" }, { "answer_id": 225222, "author": "Jordane CURE", "author_id": 92858, "author_profile": "https://wordpress.stackexchange.com/users/92858", "pm_score": 2, "selected": true, "text": "<h2>Solution</h2>\n\n<p>I find a workaround for this issue. I post it for posterity.</p>\n\n<p>This is an issue, several issue, between divi and REST Api. </p>\n\n<p>In the exemple bellow, <code>register_rest_field</code> is used instead of <code>register_rest_route</code>, but the fix is valid for both method.</p>\n\n<p>This solution could not be very futureproof. But, at least, their is no modification inside Divi Builder or Rest API. </p>\n\n<pre><code>/*\n Edit Rest call\n*/\nadd_action( 'rest_api_init', function ()\n{\n register_rest_field(\n 'page',\n 'content',\n array(\n 'get_callback' =&gt; 'duo_get_divi_content',\n 'update_callback' =&gt; null,\n 'schema' =&gt; null,\n )\n );\n});\n\nfunction duo_get_divi_content( $object, $field_name, $request )\n{\n //Set is_singular to true to ovoid \"read more issue\"\n //Issue come from is_singular () in divi-builder.php line 73\n global $wp_query;\n $wp_query-&gt;is_singular = true;\n\n\n //Set divi shortcode\n //The 2 function bellow are define in 'init' but they are call in 'wp'\n //REST Api exit after 'parse_request' hook, it's before 'wp' so divi's shortcode are not set\n et_builder_init_global_settings ();\n et_builder_add_main_elements ();\n\n\n //Define $post, if not defined, divi will not add outter_content and inner_content warper\n //Issue come from get_the_ID() in divi-builder.php line 69\n global $post;\n $post = get_post ($object['id']);\n\n //Apply the_content's filter, one of them interpret shortcodes\n $output = apply_filters( 'the_content', $post-&gt;post_content );\n\n return $output;\n}\n</code></pre>\n" } ]
2016/04/27
[ "https://wordpress.stackexchange.com/questions/224984", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93113/" ]
I'm trying to change the category for all posts of an author. I've been looking on here for about an hour and haven't found a solution.. Any help would be greatly appreciated :) Thanks, j03
Solution -------- I find a workaround for this issue. I post it for posterity. This is an issue, several issue, between divi and REST Api. In the exemple bellow, `register_rest_field` is used instead of `register_rest_route`, but the fix is valid for both method. This solution could not be very futureproof. But, at least, their is no modification inside Divi Builder or Rest API. ``` /* Edit Rest call */ add_action( 'rest_api_init', function () { register_rest_field( 'page', 'content', array( 'get_callback' => 'duo_get_divi_content', 'update_callback' => null, 'schema' => null, ) ); }); function duo_get_divi_content( $object, $field_name, $request ) { //Set is_singular to true to ovoid "read more issue" //Issue come from is_singular () in divi-builder.php line 73 global $wp_query; $wp_query->is_singular = true; //Set divi shortcode //The 2 function bellow are define in 'init' but they are call in 'wp' //REST Api exit after 'parse_request' hook, it's before 'wp' so divi's shortcode are not set et_builder_init_global_settings (); et_builder_add_main_elements (); //Define $post, if not defined, divi will not add outter_content and inner_content warper //Issue come from get_the_ID() in divi-builder.php line 69 global $post; $post = get_post ($object['id']); //Apply the_content's filter, one of them interpret shortcodes $output = apply_filters( 'the_content', $post->post_content ); return $output; } ```
224,989
<p>I was trying to update my wordpress core to 4.5.1 but my system was missing some permissions, and now after giving correct permission, I cannot get rid of that message and I cannot upgrade. Tried to look for a .maintainance file but there is not.</p> <p>How do I update now?</p> <p>Thanks for help</p>
[ { "answer_id": 226009, "author": "Alexander Ushakov", "author_id": 93707, "author_profile": "https://wordpress.stackexchange.com/users/93707", "pm_score": 7, "selected": false, "text": "<p>It is an automatic lock to prevent simultaneous core updates. It will be gone after 15 minutes. If you don't want to wait, delete the record from options table – usually <code>wp_options</code>.</p>\n\n<p>Since Wordpress 4.5:</p>\n\n<pre><code>option_name = 'core_updater.lock'\n</code></pre>\n\n<p>If you have an <strong>older</strong> installation (before Wordpress 4.5):</p>\n\n<pre><code>option_name = 'core_updater' \n</code></pre>\n" }, { "answer_id": 247670, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 0, "selected": false, "text": "<p>Confirming this <code>'core_updater.lock'</code>. It may not be obvious at first but look at the line <code>771</code>.</p>\n\n<pre><code>File: wp-admin/includes/class-wp-upgrader.php\n754: /**\n755: * Creates a lock using WordPress options.\n756: *\n757: * @since 4.5.0\n758: * @access public\n759: * @static\n760: *\n761: * @param string $lock_name The name of this unique lock.\n762: * @param int $release_timeout Optional. The duration in seconds to respect an existing lock.\n763: * Default: 1 hour.\n764: * @return bool False if a lock couldn't be created or if the lock is no longer valid. True otherwise.\n765: */\n766: public static function create_lock( $lock_name, $release_timeout = null ) {\n767: global $wpdb;\n768: if ( ! $release_timeout ) {\n769: $release_timeout = HOUR_IN_SECONDS;\n770: }\n771: $lock_option = $lock_name . '.lock';\n772: \n773: // Try to lock.\n774: $lock_result = $wpdb-&gt;query( $wpdb-&gt;prepare( \"INSERT IGNORE INTO `$wpdb-&gt;options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */\", $lock_option, time() ) );\n775: \n</code></pre>\n\n<p>Now, if you like you may <a href=\"http://wp-cli.org/commands/option/\" rel=\"nofollow noreferrer\">delete</a> this option:</p>\n\n<pre><code>$&gt;wp option delete core_updater.lock\n</code></pre>\n" }, { "answer_id": 274489, "author": "Ian Svoboda", "author_id": 86773, "author_profile": "https://wordpress.stackexchange.com/users/86773", "pm_score": 1, "selected": false, "text": "<p>Per @jeremyclarke, running this at the terminal resolved this issue for me:\n<code>wp option delete core_updater.lock</code></p>\n" }, { "answer_id": 275638, "author": "Jewel", "author_id": 16705, "author_profile": "https://wordpress.stackexchange.com/users/16705", "pm_score": 5, "selected": false, "text": "<p>If you use wp-cli run the following command:</p>\n\n<pre><code>wp option delete core_updater.lock\n</code></pre>\n\n<p>This command will delete the option named: <code>core_updater.lock</code></p>\n" }, { "answer_id": 311461, "author": "John Dee", "author_id": 131224, "author_profile": "https://wordpress.stackexchange.com/users/131224", "pm_score": 3, "selected": false, "text": "<p>Add this code to any plugin or your theme's <strong>functions.php</strong> file. Remember to remove it when you're done to prevent flicking your database for no reason.</p>\n\n<pre><code>delete_option( \"core_updater.lock\" );\n</code></pre>\n" }, { "answer_id": 357425, "author": "Jonathan", "author_id": 41070, "author_profile": "https://wordpress.stackexchange.com/users/41070", "pm_score": 0, "selected": false, "text": "<p>For anyone looking for the full MySQL query:</p>\n\n<p><code>DELETE FROM wp_options WHERE option_name LIKE '%core_update%' LIMIT 1</code></p>\n" }, { "answer_id": 365135, "author": "maheshwaghmare", "author_id": 52167, "author_profile": "https://wordpress.stackexchange.com/users/52167", "pm_score": 0, "selected": false, "text": "<p>In WordPress there are two update locks:</p>\n\n<ul>\n<li>core_updater</li>\n<li>auto_updater</li>\n</ul>\n\n<p>So, you can fix this by deleting the update locks.</p>\n\n<p>Use below code to delete the lock's:</p>\n\n<pre><code>delete_option( 'core_updater.lock' );\ndelete_option( 'auto_updater.lock' );\n</code></pre>\n\n<p>You can delete the update locks with CLI command too. Checkout how to <a href=\"https://wp.me/p4Ams0-15y\" rel=\"nofollow noreferrer\">delete them with CLI</a> command.</p>\n\n<p>Use the WordPress plugin<a href=\"https://i2.wp.com/maheshwaghmare.com/wp-content/uploads/2020/05/fix-wordpress-another-update-is-currently-in-progress.png?resize=1024%2C493&amp;ssl=1\" rel=\"nofollow noreferrer\">enter link description here</a> \n<a href=\"https://wordpress.org/plugins/fix-update-in-process/\" rel=\"nofollow noreferrer\">fix-update-in-process</a> which show the existing locks and fix the issue with one click.</p>\n" } ]
2016/04/27
[ "https://wordpress.stackexchange.com/questions/224989", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93040/" ]
I was trying to update my wordpress core to 4.5.1 but my system was missing some permissions, and now after giving correct permission, I cannot get rid of that message and I cannot upgrade. Tried to look for a .maintainance file but there is not. How do I update now? Thanks for help
It is an automatic lock to prevent simultaneous core updates. It will be gone after 15 minutes. If you don't want to wait, delete the record from options table – usually `wp_options`. Since Wordpress 4.5: ``` option_name = 'core_updater.lock' ``` If you have an **older** installation (before Wordpress 4.5): ``` option_name = 'core_updater' ```
225,002
<p>I'm working on a theme for a travel blog and the author likes to insert small images in the text of their posts (<a href="http://tracysbackpack.com/2016/04/flying-2400-miles-to-see-hamilton/" rel="nofollow">an example is here</a>).</p> <p>I want the images to alternatingly float left or right (so the first image floats left then the next floats right, etc). I know with CSS you can use pseudo-classes like nth-of-type to apply styles to every other item but it doesn't seem to be working in this case because they aren't a bunch of sibling img items all next to each other, they're img items buried within paragraphs of the post.</p> <p>How can I go about applying alternating styling to the images in the posts in this scenario?</p>
[ { "answer_id": 226009, "author": "Alexander Ushakov", "author_id": 93707, "author_profile": "https://wordpress.stackexchange.com/users/93707", "pm_score": 7, "selected": false, "text": "<p>It is an automatic lock to prevent simultaneous core updates. It will be gone after 15 minutes. If you don't want to wait, delete the record from options table – usually <code>wp_options</code>.</p>\n\n<p>Since Wordpress 4.5:</p>\n\n<pre><code>option_name = 'core_updater.lock'\n</code></pre>\n\n<p>If you have an <strong>older</strong> installation (before Wordpress 4.5):</p>\n\n<pre><code>option_name = 'core_updater' \n</code></pre>\n" }, { "answer_id": 247670, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 0, "selected": false, "text": "<p>Confirming this <code>'core_updater.lock'</code>. It may not be obvious at first but look at the line <code>771</code>.</p>\n\n<pre><code>File: wp-admin/includes/class-wp-upgrader.php\n754: /**\n755: * Creates a lock using WordPress options.\n756: *\n757: * @since 4.5.0\n758: * @access public\n759: * @static\n760: *\n761: * @param string $lock_name The name of this unique lock.\n762: * @param int $release_timeout Optional. The duration in seconds to respect an existing lock.\n763: * Default: 1 hour.\n764: * @return bool False if a lock couldn't be created or if the lock is no longer valid. True otherwise.\n765: */\n766: public static function create_lock( $lock_name, $release_timeout = null ) {\n767: global $wpdb;\n768: if ( ! $release_timeout ) {\n769: $release_timeout = HOUR_IN_SECONDS;\n770: }\n771: $lock_option = $lock_name . '.lock';\n772: \n773: // Try to lock.\n774: $lock_result = $wpdb-&gt;query( $wpdb-&gt;prepare( \"INSERT IGNORE INTO `$wpdb-&gt;options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */\", $lock_option, time() ) );\n775: \n</code></pre>\n\n<p>Now, if you like you may <a href=\"http://wp-cli.org/commands/option/\" rel=\"nofollow noreferrer\">delete</a> this option:</p>\n\n<pre><code>$&gt;wp option delete core_updater.lock\n</code></pre>\n" }, { "answer_id": 274489, "author": "Ian Svoboda", "author_id": 86773, "author_profile": "https://wordpress.stackexchange.com/users/86773", "pm_score": 1, "selected": false, "text": "<p>Per @jeremyclarke, running this at the terminal resolved this issue for me:\n<code>wp option delete core_updater.lock</code></p>\n" }, { "answer_id": 275638, "author": "Jewel", "author_id": 16705, "author_profile": "https://wordpress.stackexchange.com/users/16705", "pm_score": 5, "selected": false, "text": "<p>If you use wp-cli run the following command:</p>\n\n<pre><code>wp option delete core_updater.lock\n</code></pre>\n\n<p>This command will delete the option named: <code>core_updater.lock</code></p>\n" }, { "answer_id": 311461, "author": "John Dee", "author_id": 131224, "author_profile": "https://wordpress.stackexchange.com/users/131224", "pm_score": 3, "selected": false, "text": "<p>Add this code to any plugin or your theme's <strong>functions.php</strong> file. Remember to remove it when you're done to prevent flicking your database for no reason.</p>\n\n<pre><code>delete_option( \"core_updater.lock\" );\n</code></pre>\n" }, { "answer_id": 357425, "author": "Jonathan", "author_id": 41070, "author_profile": "https://wordpress.stackexchange.com/users/41070", "pm_score": 0, "selected": false, "text": "<p>For anyone looking for the full MySQL query:</p>\n\n<p><code>DELETE FROM wp_options WHERE option_name LIKE '%core_update%' LIMIT 1</code></p>\n" }, { "answer_id": 365135, "author": "maheshwaghmare", "author_id": 52167, "author_profile": "https://wordpress.stackexchange.com/users/52167", "pm_score": 0, "selected": false, "text": "<p>In WordPress there are two update locks:</p>\n\n<ul>\n<li>core_updater</li>\n<li>auto_updater</li>\n</ul>\n\n<p>So, you can fix this by deleting the update locks.</p>\n\n<p>Use below code to delete the lock's:</p>\n\n<pre><code>delete_option( 'core_updater.lock' );\ndelete_option( 'auto_updater.lock' );\n</code></pre>\n\n<p>You can delete the update locks with CLI command too. Checkout how to <a href=\"https://wp.me/p4Ams0-15y\" rel=\"nofollow noreferrer\">delete them with CLI</a> command.</p>\n\n<p>Use the WordPress plugin<a href=\"https://i2.wp.com/maheshwaghmare.com/wp-content/uploads/2020/05/fix-wordpress-another-update-is-currently-in-progress.png?resize=1024%2C493&amp;ssl=1\" rel=\"nofollow noreferrer\">enter link description here</a> \n<a href=\"https://wordpress.org/plugins/fix-update-in-process/\" rel=\"nofollow noreferrer\">fix-update-in-process</a> which show the existing locks and fix the issue with one click.</p>\n" } ]
2016/04/27
[ "https://wordpress.stackexchange.com/questions/225002", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92529/" ]
I'm working on a theme for a travel blog and the author likes to insert small images in the text of their posts ([an example is here](http://tracysbackpack.com/2016/04/flying-2400-miles-to-see-hamilton/)). I want the images to alternatingly float left or right (so the first image floats left then the next floats right, etc). I know with CSS you can use pseudo-classes like nth-of-type to apply styles to every other item but it doesn't seem to be working in this case because they aren't a bunch of sibling img items all next to each other, they're img items buried within paragraphs of the post. How can I go about applying alternating styling to the images in the posts in this scenario?
It is an automatic lock to prevent simultaneous core updates. It will be gone after 15 minutes. If you don't want to wait, delete the record from options table – usually `wp_options`. Since Wordpress 4.5: ``` option_name = 'core_updater.lock' ``` If you have an **older** installation (before Wordpress 4.5): ``` option_name = 'core_updater' ```
225,032
<p>Is it possible to add a piece of code snippets inside wordpress standard function ? In my case I am developing a plugin that will trace the exact location of the caller of wp_delete_attachment method in wordpress. I can acheive that by <strong>debug_backtrace()</strong> but this method must be called inside the method you wish to trace. How can I acheive this without touching/ editing the wordpress core functions ?</p> <pre><code>function wp_delete_attachment( $post_id, $force_delete = false ) { &lt;-- wordpress core function global $wpdb; //my custom code inside wordpress core function $bt = debug_backtrace(); $caller = array_shift($bt); die(json_encode($caller)); } </code></pre>
[ { "answer_id": 225035, "author": "RRikesh", "author_id": 17305, "author_profile": "https://wordpress.stackexchange.com/users/17305", "pm_score": 1, "selected": false, "text": "<p>It depends what you want to do.</p>\n\n<p>If you look into the <a href=\"https://developer.wordpress.org/reference/functions/wp_delete_attachment/#source-code\" rel=\"nofollow\">function definition</a>, you'll notice some <a href=\"https://developer.wordpress.org/reference/functions/do_action/\" rel=\"nofollow\">do_action()</a>:</p>\n\n<p>For example:</p>\n\n<pre><code>do_action( 'delete_attachment', $post_id );\ndo_action( 'delete_post', $post_id );\ndo_action( 'deleted_post', $post_id );\n</code></pre>\n\n<p>These are points, called hooks in WordPress, where you can actually run your stuff. Hooks will help you to modify the core behaviour without modifying the WordPress core itself. </p>\n\n<p>Let's assume you want to hook into the code before the attachment is deleted, you can then use <code>add_action('delete_attachement', 'yourfunction');</code> in your plugin or theme's <code>functions.php</code> to run any code you want.</p>\n\n<p>For example:</p>\n\n<pre><code>add_action('delete_attachement', 'yourfunction');\n\nfunction yourfunction( $post_id ){\n echo 'sample';\n die;\n}\n</code></pre>\n" }, { "answer_id": 225241, "author": "shramee", "author_id": 92887, "author_profile": "https://wordpress.stackexchange.com/users/92887", "pm_score": 0, "selected": false, "text": "<p>You need to hook your function to <code>delete_attachement</code> hook, but you also need to remove some extra functions that are called before calling your hooked action to reach the right caller of <code>wp_delete_attachment()</code>.</p>\n\n<p>Here's a possible implementation...</p>\n\n<pre><code>function my_backtrace( $post_id ) {\n $bt = debug_backtrace();\n array_shift( $bt ); // Remove reference to function\n array_shift( $bt ); // Remove reference to call_user_func_array\n array_shift( $bt ); // Remove reference to do_action\n array_shift( $bt ); // Remove reference to wp_delete_attachment\n $caller = array_shift( $bt ); // This is what called wp_delete_attachment\n die( '&lt;pre&gt;' . json_encode( $caller, JSON_PRETTY_PRINT ) . '&lt;/pre&gt;' );\n}\nadd_action('delete_attachement', 'my_backtrace');\n</code></pre>\n\n<p>Also you can use <code>json_encode( $caller, JSON_PRETTY_PRINT )</code> to pretty print your encoded JSON ;)</p>\n\n<p>Lemme know how it works for you...</p>\n\n<p>Cheers</p>\n" }, { "answer_id": 225348, "author": "Danryl Carpio", "author_id": 93014, "author_profile": "https://wordpress.stackexchange.com/users/93014", "pm_score": 1, "selected": true, "text": "<p>I solve the problem by hooking my function to <code>delete_attachment</code> hook, then putting the debug trace inside my function and filtering the <code>wp_delete_attachment</code>, by this I can retrieve what file and line number where the wp_delete_attachment is called. </p>\n\n<pre><code>add_action( 'delete_attachment', 'your_function' );\nfunction your_function($postid) {\n $trace = debug_backtrace();\n\n if(is_array($trace) &amp;&amp; !empty($trace)) { \n foreach ($trace as $trace_value) {\n if(array_key_exists(\"function\", $trace_value)) {\n if($trace_value['function'] == \"wp_delete_attachment\") {\n\n echo $trace_value;\n\n }\n }\n }\n }\n}\n</code></pre>\n" } ]
2016/04/28
[ "https://wordpress.stackexchange.com/questions/225032", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93014/" ]
Is it possible to add a piece of code snippets inside wordpress standard function ? In my case I am developing a plugin that will trace the exact location of the caller of wp\_delete\_attachment method in wordpress. I can acheive that by **debug\_backtrace()** but this method must be called inside the method you wish to trace. How can I acheive this without touching/ editing the wordpress core functions ? ``` function wp_delete_attachment( $post_id, $force_delete = false ) { <-- wordpress core function global $wpdb; //my custom code inside wordpress core function $bt = debug_backtrace(); $caller = array_shift($bt); die(json_encode($caller)); } ```
I solve the problem by hooking my function to `delete_attachment` hook, then putting the debug trace inside my function and filtering the `wp_delete_attachment`, by this I can retrieve what file and line number where the wp\_delete\_attachment is called. ``` add_action( 'delete_attachment', 'your_function' ); function your_function($postid) { $trace = debug_backtrace(); if(is_array($trace) && !empty($trace)) { foreach ($trace as $trace_value) { if(array_key_exists("function", $trace_value)) { if($trace_value['function'] == "wp_delete_attachment") { echo $trace_value; } } } } } ```
225,067
<p>I am receiving many requests to my wp-login.php and xmlrpc file, now I just set up an htaccess to prevent requests to xmlrpc, but how do you suggest me to block wp-login?</p> <p>thanks</p>
[ { "answer_id": 241512, "author": "Feriman", "author_id": 78021, "author_profile": "https://wordpress.stackexchange.com/users/78021", "pm_score": 0, "selected": false, "text": "<p>Try it to paste in your .htaccess file:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine on\nRewriteCond %{REQUEST_METHOD} POST\nRewriteCond %{HTTP_REFERER} !^http://(.*)?example\\.com [NC]\nRewriteCond %{REQUEST_URI} ^/(.*)?wp-login\\.php(.*)$ [OR]\nRewriteCond %{REQUEST_URI} ^/(.*)?wp-admin$\nRewriteRule ^(.*)$ - [R=403,L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>Replace <code>example.com</code> to your domain name.</p>\n" }, { "answer_id": 241525, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 1, "selected": false, "text": "<p>Additionally to using htaccess, you can disable the XML-RPC function by adding the following to your child theme's <code>functions.php</code>:</p>\n\n<pre><code># Set XML-RPC features to false\nadd_filter( 'xmlrpc_enabled', '__return_false' );\nadd_filter( 'pre_option_enable_xmlrpc', '__return_zero' );\n</code></pre>\n" }, { "answer_id": 241540, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 0, "selected": false, "text": "<p>Actually, I advise to you protection plugin, like <code>iThemes Security</code>. It has the excellent feature: to hide <code>wp-login.php</code> and instead, you can set custom url for login (and hackers cant find that url, of course, if you wont reveal that link in internet).</p>\n" } ]
2016/04/28
[ "https://wordpress.stackexchange.com/questions/225067", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93040/" ]
I am receiving many requests to my wp-login.php and xmlrpc file, now I just set up an htaccess to prevent requests to xmlrpc, but how do you suggest me to block wp-login? thanks
Additionally to using htaccess, you can disable the XML-RPC function by adding the following to your child theme's `functions.php`: ``` # Set XML-RPC features to false add_filter( 'xmlrpc_enabled', '__return_false' ); add_filter( 'pre_option_enable_xmlrpc', '__return_zero' ); ```
225,075
<p>Which WordPress function allows you to include the <code>footer.php</code> file into <code>index.php</code> file?</p>
[ { "answer_id": 225077, "author": "Michael Wilson", "author_id": 93168, "author_profile": "https://wordpress.stackexchange.com/users/93168", "pm_score": 3, "selected": true, "text": "<p>Add </p>\n\n<pre><code>&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>into index.php or the template you are using</p>\n\n<p>Then create footer.php and add in something like this:</p>\n\n<pre><code>&lt;?php\n /* Always have wp_footer() just before the closing &lt;/body&gt;\n * tag of your theme, or you will break many plugins, which\n * generally use this hook to reference JavaScript files.\n */\n wp_footer();\n ?&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 225097, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 0, "selected": false, "text": "<p>Found the answer here: Reference <a href=\"http://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow\">Guide</a>. It seems the default footer.php and header.php as well as some other template files are in wp-includes/theme-compat/</p>\n" } ]
2016/04/28
[ "https://wordpress.stackexchange.com/questions/225075", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59477/" ]
Which WordPress function allows you to include the `footer.php` file into `index.php` file?
Add ``` <?php get_footer(); ?> ``` into index.php or the template you are using Then create footer.php and add in something like this: ``` <?php /* Always have wp_footer() just before the closing </body> * tag of your theme, or you will break many plugins, which * generally use this hook to reference JavaScript files. */ wp_footer(); ?> </body> </html> ```
225,083
<p>I'm using wp cli to import the same featured image for around 2,000 posts. I did a couple tests to see if the image would be duplicated or if WordPress would notice that the image already exists in the media library and use it. Sadly it just duplicates the image. </p> <p>Command I'm using: <code>wp media import http://example.com/wp-content/uploads/sites/30/2016/04/picture_name.jpg --post_id=x --title="Pluto Mosaic" --featured_image --url=mysite.example.com</code> </p> <p>Is there another way to do this without having to import the same image 2,000 times?</p> <p>Thanks, j03</p>
[ { "answer_id": 225116, "author": "Aric Watson", "author_id": 81449, "author_profile": "https://wordpress.stackexchange.com/users/81449", "pm_score": 0, "selected": false, "text": "<p>You should be able to write a php script to do this for each post. You'll need to do a query to get all the posts, then loop through that setting the featured image to your desired image on each post.</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/100838/how-to-set-featured-image-to-custom-post-from-outside-programmatically\">This question</a> has specific code that should get you started.</p>\n" }, { "answer_id": 225230, "author": "Daniel Bachhuber", "author_id": 82349, "author_profile": "https://wordpress.stackexchange.com/users/82349", "pm_score": 3, "selected": true, "text": "<p>You can use <code>wp media import</code> to import the image once. Once you have the ID for the attachment created, you can run:</p>\n\n<pre><code>wp post list --post_type=post --format=ids | xargs -0 -d ' ' -I % wp post meta add % _thumbnail_id &lt;thumbnail-id&gt;\n</code></pre>\n\n<p>Make sure to replace <code>&lt;thumbnail-id&gt;</code> with the actual attachment ID.</p>\n" }, { "answer_id": 339879, "author": "Trect", "author_id": 160004, "author_profile": "https://wordpress.stackexchange.com/users/160004", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://dev-notes.eu/2016/07/bulk-import-images-using-wp-cli/\" rel=\"nofollow noreferrer\">This</a> Worked for me very well.</p>\n\n<pre><code># Line 1\nATT_ID=\"$(wp media import ~/Pictures/swimming.jpg --porcelain)\"\n# Line 2\nwp post list --post_type=post --format=ids | \\\n# Line 3\nxargs -0 -d ' ' -I % wp post meta add % \\_thumbnail_id $ATT_ID\n</code></pre>\n\n<p>Walkthrough:</p>\n\n<p>The <code>--porcelain</code> option causes the new attachment ID to be output, so this line runs the import and sets the <code>$ATT_ID</code> shell variable to the imported image ID\n <code>wp post list --post_type=post --format=ids</code> gets a list of post IDs in a space-separated string format and passes this to <code>xargs</code>\n <code>xargs</code> operates on each ID, setting the post meta <code>_thumbnail_id</code> field for each post ID. The <code>xargs</code> options set a space as the delimiter.</p>\n" } ]
2016/04/28
[ "https://wordpress.stackexchange.com/questions/225083", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93113/" ]
I'm using wp cli to import the same featured image for around 2,000 posts. I did a couple tests to see if the image would be duplicated or if WordPress would notice that the image already exists in the media library and use it. Sadly it just duplicates the image. Command I'm using: `wp media import http://example.com/wp-content/uploads/sites/30/2016/04/picture_name.jpg --post_id=x --title="Pluto Mosaic" --featured_image --url=mysite.example.com` Is there another way to do this without having to import the same image 2,000 times? Thanks, j03
You can use `wp media import` to import the image once. Once you have the ID for the attachment created, you can run: ``` wp post list --post_type=post --format=ids | xargs -0 -d ' ' -I % wp post meta add % _thumbnail_id <thumbnail-id> ``` Make sure to replace `<thumbnail-id>` with the actual attachment ID.
225,085
<p>The code below gets the image but I want it to be a background image. I believe I need to save the image as a variable first and then echo it out somehow. My PHP is not great so please give an example using the code. No esoteric answers, thanks.</p> <pre><code>&lt;div class="main-slider" class="flexslider"&gt; &lt;ul class="slides"&gt; &lt;?php // Get all posts in 'slider' category $post_categories = wp_get_post_categories( $post_id ); $args = array( 'post_type' =&gt; array( 'Interaction', 'Print', 'Motion', 'Image', 'Sound' ), 'numberposts' =&gt; 6, 'category_name' =&gt; 'slider' ); $postQuery = get_posts( $args ); foreach( $postQuery as $post ) : setup_postdata($post); if ( has_post_thumbnail() ) { ?&gt; &lt;li class="frontSlider"&gt;&lt;?php the_post_thumbnail('feature-slider'); ?&gt; &lt;a href="&lt;?php echo get_permalink(); ?&gt;" title="Go to &lt;?php echo the_title(); ?&gt;" rel="bookmark"&gt; &lt;div class="flex-captionWrap"&gt; &lt;p class="flex-caption"&gt;&lt;?php echo get_post(get_post_thumbnail_id())-&gt;post_excerpt; ?&gt;&lt;/p&gt;&lt;!-- Retrieves text string from Captions field in Media --&gt; &lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php } endforeach; ?&gt; &lt;/ul&gt;&lt;!-- .flexslider --&gt; &lt;/div&gt;&lt;!-- .flexslider --&gt; </code></pre>
[ { "answer_id": 225087, "author": "mread1208", "author_id": 70293, "author_profile": "https://wordpress.stackexchange.com/users/70293", "pm_score": 3, "selected": true, "text": "<p>You are correct, you will need to get the image URL and set is as a variable so you can echo it out as an inline style in your HTML. I've updated your foreach loop below and set the image as an inline style of your <code>&lt;li&gt;</code> element:</p>\n\n<pre><code>foreach( $postQuery as $post ) : setup_postdata($post);\n if ( has_post_thumbnail() ) { ?&gt;\n /* Get the post thumbnail source so we can get the exact URL of the image. This returns an array of stuff for us */\n $thumbImg = wp_get_attachment_image_src( get_post_thumbnail_id($post-&gt;ID), 'feature-slider' );\n /* Since we want the URL, let's get the first value from our new array and set it as $thumbImgUrl */\n $thumbImgUrl = $thumbImg['0']; ?&gt;\n &lt;li class=\"frontSlider\" style=\"background-image: url('&lt;?php echo $thumbImgUrl; ?&gt;');\"&gt;\n &lt;a href=\"&lt;?php echo get_permalink(); ?&gt;\" title=\"Go to &lt;?php echo the_title(); ?&gt;\" rel=\"bookmark\"&gt;\n &lt;div class=\"flex-captionWrap\"&gt;\n &lt;p class=\"flex-caption\"&gt;&lt;?php echo get_post(get_post_thumbnail_id())-&gt;post_excerpt; ?&gt;&lt;/p&gt;&lt;!-- Retrieves text string from Captions field in Media --&gt;\n &lt;/div&gt;\n &lt;/a&gt;\n &lt;/li&gt;\n &lt;?php \n }\nendforeach; ?&gt;\n</code></pre>\n\n<p>Hope that helps! I did not test this before posting it, but I've done this several times before so it should work just fine.</p>\n" }, { "answer_id": 225088, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>There's a couple things that you need to do to get the URL - you could combine them into one long sentence probably but I'll break it down.</p>\n\n<p>WordPress stores the thumbnail ID in the postmeta table as <code>_thumbnail_id</code> so we need to get that using <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow\"><code>get_post_meta()</code></a>:</p>\n\n<pre><code>$thumb_id = get_post_meta( $post-&gt;ID, '_thumbnail_id', true );\n</code></pre>\n\n<p>Now that we have the ID we need to get the URL. Since we need the actual file URL we <strong>cannot</strong> use <code>get_permalink()</code> as that will return an attachment page so we instead need to use <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow\"><code>wp_get_attachment_image_src()</code></a> which returns an array of values.</p>\n\n<pre><code>$img_arr = wp_get_attachment_image_src( $thumb_id, 'feature-slider' );\n</code></pre>\n\n<p>Looking at the codex we know that index <code>0</code> holds the actual image URL, so we can place it right in our list item:</p>\n\n<pre><code>&lt;li class=\"frontSlider\" style=\"background-image: url( '&lt;?php echo $img_arr[0]; ?&gt;' );\"&gt;\n</code></pre>\n\n<p>Then in our CSS we can apply any further styles we need.</p>\n" } ]
2016/04/28
[ "https://wordpress.stackexchange.com/questions/225085", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80362/" ]
The code below gets the image but I want it to be a background image. I believe I need to save the image as a variable first and then echo it out somehow. My PHP is not great so please give an example using the code. No esoteric answers, thanks. ``` <div class="main-slider" class="flexslider"> <ul class="slides"> <?php // Get all posts in 'slider' category $post_categories = wp_get_post_categories( $post_id ); $args = array( 'post_type' => array( 'Interaction', 'Print', 'Motion', 'Image', 'Sound' ), 'numberposts' => 6, 'category_name' => 'slider' ); $postQuery = get_posts( $args ); foreach( $postQuery as $post ) : setup_postdata($post); if ( has_post_thumbnail() ) { ?> <li class="frontSlider"><?php the_post_thumbnail('feature-slider'); ?> <a href="<?php echo get_permalink(); ?>" title="Go to <?php echo the_title(); ?>" rel="bookmark"> <div class="flex-captionWrap"> <p class="flex-caption"><?php echo get_post(get_post_thumbnail_id())->post_excerpt; ?></p><!-- Retrieves text string from Captions field in Media --> </div> </a> </li> <?php } endforeach; ?> </ul><!-- .flexslider --> </div><!-- .flexslider --> ```
You are correct, you will need to get the image URL and set is as a variable so you can echo it out as an inline style in your HTML. I've updated your foreach loop below and set the image as an inline style of your `<li>` element: ``` foreach( $postQuery as $post ) : setup_postdata($post); if ( has_post_thumbnail() ) { ?> /* Get the post thumbnail source so we can get the exact URL of the image. This returns an array of stuff for us */ $thumbImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'feature-slider' ); /* Since we want the URL, let's get the first value from our new array and set it as $thumbImgUrl */ $thumbImgUrl = $thumbImg['0']; ?> <li class="frontSlider" style="background-image: url('<?php echo $thumbImgUrl; ?>');"> <a href="<?php echo get_permalink(); ?>" title="Go to <?php echo the_title(); ?>" rel="bookmark"> <div class="flex-captionWrap"> <p class="flex-caption"><?php echo get_post(get_post_thumbnail_id())->post_excerpt; ?></p><!-- Retrieves text string from Captions field in Media --> </div> </a> </li> <?php } endforeach; ?> ``` Hope that helps! I did not test this before posting it, but I've done this several times before so it should work just fine.
225,089
<p>I just trasformed an old website to a one-page Wordpress.</p> <p>The old website had several URLS, now there's ony 1: the homepage. Plus another page with privacy policy.</p> <p>Hence I would like to redirect all URLS except the one with slug "privacy" to the homepage.</p> <p>This is what I'm trying, without success:</p> <pre><code>#custom redirects &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteCond %{REQUEST_URI} !^/privacy-policy/ RewriteRule (.*) http://www.mywebsite.com/$1 [R=301,L] &lt;/IfModule&gt; # BEGIN WordPress (standard wp htaccess rules) &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>I get too many redirect: all urls redirect infinitely to themselves, why?</p> <p>would be better (if possibile) using a redirect rule instead of a rewrite?</p> <p><strong>UPDATE</strong></p> <p>following comments suggestion I tried the following custom redirects (before WP standard rules):</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteCond %{REQUEST_URI} !^/privacy-policy$ RewriteRule (.*) http://mywebsite.com/ [R=301,L] &lt;/IfModule&gt; </code></pre> <p>But still not working</p>
[ { "answer_id": 225101, "author": "Florian", "author_id": 52583, "author_profile": "https://wordpress.stackexchange.com/users/52583", "pm_score": 0, "selected": false, "text": "<p>Please try </p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteRule ^/privacy-policy/? privacy-policy [L,NC]\n\nRewriteCond %{HTTP_HOST} ^(www\\.)?oldsite\\.com [NC]\nRewriteRule ^ http://mywebsite.com%{REQUEST_URI} [NE,R=301,L]\n&lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 225149, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 2, "selected": false, "text": "<h2>Problems</h2>\n\n<blockquote>\n <p>I get too many redirect: all urls redirect infinitely to themselves, why?</p>\n</blockquote>\n\n<p>Apache rewrite rules are processed top-to-bottom, so your custom rewrite rule is always processed first. The <code>R</code> redirect flag instructs Apache to tell the browser to make a new request to the altered URL instead of serving the destination of the rewrite at the current address, and the <code>L</code> \"last\" flag tells Apache to ignore all proceeding rewrite rules - so whenever your <code>RewriteRule</code> is applied, a new request is made and your rules are processed once again from the top.</p>\n\n<p>Your <code>RewriteCond</code> instructs Apache to process the proceeding <code>RewriteRule</code> whenever the request URI path does not begin with <code>/privacy-policy</code> - so virtually every request is resulting in a redirect before any of the other rules in your <code>.htaccess</code> can be so much as evaluated.</p>\n\n<p>As @MarkKaplun alluded to in the comments <code>$1</code> is a back-reference that's substituted with the portion of the matched URI contained in the first \"capture-group\" (the first set of parenthesis in the pattern). Since <code>.*</code> literally matches any number of any characters, in your <code>RewriteRule</code> <code>$1</code> is substituted with the <em>entire</em> URI path.</p>\n\n<p>In essence, your rewrite rules:</p>\n\n<pre><code>RewriteCond %{REQUEST_URI} !^/privacy-policy/\nRewriteRule (.*) http://www.mywebsite.com/$1 [R=301,L]\n</code></pre>\n\n<p>evaluate to <em>\"If the URI does not begin with <code>/privacy-policy/</code>, have the web-browser send a new request to <code>http://www.mywebsite.com/(original URI path)</code>\"</em>.</p>\n\n<p>So, for illustrative purposes, say you navigated to <code>http://www.mywebsite.com/blog/2015</code>; here's what happens with each request:</p>\n\n<ol>\n<li><code>/blog/2015</code> does not start with <code>/privacy-policy/</code>, tell the browser to go to <code>http://www.mywebsite.com/blog/2015</code>.</li>\n<li><code>/blog/2015</code> does not start with <code>/privacy-policy/</code>, tell the browser to go to <code>http://www.mywebsite.com/blog/2015</code>.</li>\n<li><code>/blog/2015</code> does not start with <code>/privacy-policy/</code>, tell the browser to go to <code>http://www.mywebsite.com/blog/2015</code>.</li>\n<li>[...]</li>\n</ol>\n\n<p>Removing the <code>$1</code> back-reference from the <code>RewriteRule</code> is insufficient, as a URI path of <code>/</code> (or a simply empty one) still does not qualify as beginning with <code>/privacy-policy/</code>, resulting the in the behavior:</p>\n\n<ol>\n<li><code>/blog/2015</code> does not start with <code>/privacy-policy/</code>, tell the browser to go to <code>http://www.mywebsite.com/</code>.</li>\n<li><code>/</code> does not start with <code>/privacy-policy/</code>, tell the browser to go to <code>http://www.mywebsite.com/</code>.</li>\n<li><code>/</code> does not start with <code>/privacy-policy/</code>, tell the browser to go to <code>http://www.mywebsite.com/</code>.</li>\n<li>[...]</li>\n</ol>\n\n<p>You can verify this behavior by taking a look at your Apache installation's log files.</p>\n\n<hr>\n\n<h2>Solution</h2>\n\n<p>If you don't plan on using WordPress's intended address routing, there's no reason to keep the default rewrite rules and stack more on top of them. Tailor them to your needs instead of adding complexity:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^(/|index\\.php)$ /index.php? [L]\nRewriteRule ^/?privacy-policy/?$ /index.php [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /? [L,R=301]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>In summary,</p>\n\n<ol>\n<li>.\n\n<blockquote>\n <p><strong><code>RewriteRule ^(/|index\\.php)$ /index.php? [L]</code></strong></p>\n \n <p>If <code>/</code> or <code>index.php</code> was explicitly requested, serve <code>index.php</code>, but drop the querystring (in order to prevent changing pages via query-var manipulation) and stop processing rewrites.</p>\n</blockquote></li>\n<li>. \n\n<blockquote>\n <p><strong><code>RewriteRule ^/?privacy-policy/?$ /index.php [L]</code></strong></p>\n \n <p>If <code>privacy-policy</code> (with or without leading and trailing slashes) was explicitly requested, serve <code>index.php</code> and stop processing rewrites.</p>\n</blockquote></li>\n<li>. \n\n<blockquote>\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /? [L,R=301]\n</code></pre>\n \n <p>If the requested filename is not a file and not a directory, match a single character <em>anywhere</em> (in order to apply the rule no matter the URI) and tell the browser to make a new request to <code>/</code> and discard it's querystring. Stop processing rewrites.</p>\n</blockquote></li>\n</ol>\n\n<p>It's worth noting that your intended outcome will probably produce a lot of unexpected behaviors - you'll likely be unable to access the administrative dashboard, for one. Attachments may also break. But the above should at the very least provide a good starting point for learning more about rewrite directives.</p>\n" } ]
2016/04/28
[ "https://wordpress.stackexchange.com/questions/225089", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4155/" ]
I just trasformed an old website to a one-page Wordpress. The old website had several URLS, now there's ony 1: the homepage. Plus another page with privacy policy. Hence I would like to redirect all URLS except the one with slug "privacy" to the homepage. This is what I'm trying, without success: ``` #custom redirects <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_URI} !^/privacy-policy/ RewriteRule (.*) http://www.mywebsite.com/$1 [R=301,L] </IfModule> # BEGIN WordPress (standard wp htaccess rules) <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` I get too many redirect: all urls redirect infinitely to themselves, why? would be better (if possibile) using a redirect rule instead of a rewrite? **UPDATE** following comments suggestion I tried the following custom redirects (before WP standard rules): ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_URI} !^/privacy-policy$ RewriteRule (.*) http://mywebsite.com/ [R=301,L] </IfModule> ``` But still not working
Problems -------- > > I get too many redirect: all urls redirect infinitely to themselves, why? > > > Apache rewrite rules are processed top-to-bottom, so your custom rewrite rule is always processed first. The `R` redirect flag instructs Apache to tell the browser to make a new request to the altered URL instead of serving the destination of the rewrite at the current address, and the `L` "last" flag tells Apache to ignore all proceeding rewrite rules - so whenever your `RewriteRule` is applied, a new request is made and your rules are processed once again from the top. Your `RewriteCond` instructs Apache to process the proceeding `RewriteRule` whenever the request URI path does not begin with `/privacy-policy` - so virtually every request is resulting in a redirect before any of the other rules in your `.htaccess` can be so much as evaluated. As @MarkKaplun alluded to in the comments `$1` is a back-reference that's substituted with the portion of the matched URI contained in the first "capture-group" (the first set of parenthesis in the pattern). Since `.*` literally matches any number of any characters, in your `RewriteRule` `$1` is substituted with the *entire* URI path. In essence, your rewrite rules: ``` RewriteCond %{REQUEST_URI} !^/privacy-policy/ RewriteRule (.*) http://www.mywebsite.com/$1 [R=301,L] ``` evaluate to *"If the URI does not begin with `/privacy-policy/`, have the web-browser send a new request to `http://www.mywebsite.com/(original URI path)`"*. So, for illustrative purposes, say you navigated to `http://www.mywebsite.com/blog/2015`; here's what happens with each request: 1. `/blog/2015` does not start with `/privacy-policy/`, tell the browser to go to `http://www.mywebsite.com/blog/2015`. 2. `/blog/2015` does not start with `/privacy-policy/`, tell the browser to go to `http://www.mywebsite.com/blog/2015`. 3. `/blog/2015` does not start with `/privacy-policy/`, tell the browser to go to `http://www.mywebsite.com/blog/2015`. 4. [...] Removing the `$1` back-reference from the `RewriteRule` is insufficient, as a URI path of `/` (or a simply empty one) still does not qualify as beginning with `/privacy-policy/`, resulting the in the behavior: 1. `/blog/2015` does not start with `/privacy-policy/`, tell the browser to go to `http://www.mywebsite.com/`. 2. `/` does not start with `/privacy-policy/`, tell the browser to go to `http://www.mywebsite.com/`. 3. `/` does not start with `/privacy-policy/`, tell the browser to go to `http://www.mywebsite.com/`. 4. [...] You can verify this behavior by taking a look at your Apache installation's log files. --- Solution -------- If you don't plan on using WordPress's intended address routing, there's no reason to keep the default rewrite rules and stack more on top of them. Tailor them to your needs instead of adding complexity: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^(/|index\.php)$ /index.php? [L] RewriteRule ^/?privacy-policy/?$ /index.php [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /? [L,R=301] </IfModule> ``` In summary, 1. . > > **`RewriteRule ^(/|index\.php)$ /index.php? [L]`** > > > If `/` or `index.php` was explicitly requested, serve `index.php`, but drop the querystring (in order to prevent changing pages via query-var manipulation) and stop processing rewrites. > > > 2. . > > **`RewriteRule ^/?privacy-policy/?$ /index.php [L]`** > > > If `privacy-policy` (with or without leading and trailing slashes) was explicitly requested, serve `index.php` and stop processing rewrites. > > > 3. . > > > ``` > RewriteCond %{REQUEST_FILENAME} !-f > RewriteCond %{REQUEST_FILENAME} !-d > RewriteRule . /? [L,R=301] > > ``` > > If the requested filename is not a file and not a directory, match a single character *anywhere* (in order to apply the rule no matter the URI) and tell the browser to make a new request to `/` and discard it's querystring. Stop processing rewrites. > > > It's worth noting that your intended outcome will probably produce a lot of unexpected behaviors - you'll likely be unable to access the administrative dashboard, for one. Attachments may also break. But the above should at the very least provide a good starting point for learning more about rewrite directives.
225,093
<p>In spite of many similar posts, all the proposed solutions didn't work for me, so here we are. </p> <p>I have the following script :</p> <pre><code>jQuery('#term').keyup(ajaxChange); function ajaxChange(){ var newFormChange = jQuery("#term").val(); alert (newFormChange); jQuery.ajax({ type:"POST", action: "my_test_action", url: "/wp-admin/admin-ajax.php", data: newFormChange, success:function(data){ console.log(data); } }); return false; } </code></pre> <p>And the PHP looks like this :</p> <pre><code>function my_test_action() { $var = "this is a test"; wp_send_json($var); die(); } add_action( 'wp_ajax_my_test_action', 'my_test_action' ); add_action( 'wp_ajax_nopriv_my_test_action', 'my_test_action' ); </code></pre> <p>I've also tried : <code>echo json_encode($var)</code> or <code>echo $var</code>, instead of <code>wp_send_json()</code> but the function always returns 0 in the browser console ! </p> <p>My other AJAX calls work, for instance I have another one that calls a PHP script which calls a WP Query and displays some posts, it works fine. </p> <p><strong>EDIT :</strong> Here is how my script is included :</p> <pre><code> function add_js() { if (is_page_template()) { wp_enqueue_script( 'mycustomscript', get_stylesheet_directory_uri().'/js/mycustomscript.js', array('jquery'), '1.0', true ); wp_localize_script('mycustomscript', 'ajaxurl', admin_url( 'admin-ajax.php' ) ); } } add_action('wp_enqueue_scripts', 'add_js'); </code></pre> <p>I think the problem comes from the <code>newFormChange</code> variable, because <code>jQuery(this).serialize();</code> didn't work in the first place, because the form is not submitted but only one of its fields changes. So I replaced it by var <code>newFormChange = jQuery("#term").val();</code> but then maybe there is a problem with <code>url: "/wp-admin/admin-ajax.php"</code></p> <p>Where am I mistaken ? Thanks</p>
[ { "answer_id": 225095, "author": "tam", "author_id": 18668, "author_profile": "https://wordpress.stackexchange.com/users/18668", "pm_score": 0, "selected": false, "text": "<p>It seems there is a problem with at <code>url: \"/wp-admin/admin-ajax.php\"</code>, instead try adding the full path:</p>\n\n<pre><code>function addajaxurl() {\n wp_localize_script( 'frontend-ajax', 'frontendajax', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' )));\n}\nadd_action( 'wp_enqueue_scripts', 'addajaxurl' );\n</code></pre>\n\n<p>and call the variable in your ajax function:</p>\n\n<pre><code> jQuery.ajax({\n type:\"POST\",\n url: ajaxurl,\n data: newFormChange,\n success:function(data){\n console.log(data);\n }\n }); \n</code></pre>\n" }, { "answer_id": 225096, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 4, "selected": true, "text": "<p>Note that the <code>action</code> should be inside the <code>data</code> key. In your post request there is no key named as <code>action</code> therefore, the callback function is never being called.</p>\n\n<p>Consider this example:-</p>\n\n<pre><code>jQuery.ajax({\n type:\"POST\",\n url: \"/wp-admin/admin-ajax.php\",\n data: { \n action: \"my_test_action\",\n form_data : newFormChange\n },\n success: function (data) {\n console.log(data);\n }\n});\n</code></pre>\n\n<p><strong>Also Note:</strong> Never use relative Ajax URL like <code>/wp-admin/admin-ajax.php</code>. You can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"noreferrer\"><code>wp_localize_script()</code></a>. See these <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"noreferrer\">examples</a></p>\n" }, { "answer_id": 225098, "author": "Florian", "author_id": 52583, "author_profile": "https://wordpress.stackexchange.com/users/52583", "pm_score": 0, "selected": false, "text": "<p>the problem is in the action parameter.\nIn your javascript function please try:</p>\n\n<pre><code>var newFormChange = jQuery(\"#term\").val();\n\n jQuery.ajax({\n type: \"POST\",\n url: \"/wp-admin/admin-ajax.php\",\n data: {\n action: \"my_test_action\",\n newFormChange: newFormChange\n } ,\n success: function(data) {\n console.log(data);\n alert(data);\n\n\n });\n</code></pre>\n\n<p>You should also remove die(); from your php function. It is already in the wp_send_json. </p>\n" } ]
2016/04/28
[ "https://wordpress.stackexchange.com/questions/225093", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92582/" ]
In spite of many similar posts, all the proposed solutions didn't work for me, so here we are. I have the following script : ``` jQuery('#term').keyup(ajaxChange); function ajaxChange(){ var newFormChange = jQuery("#term").val(); alert (newFormChange); jQuery.ajax({ type:"POST", action: "my_test_action", url: "/wp-admin/admin-ajax.php", data: newFormChange, success:function(data){ console.log(data); } }); return false; } ``` And the PHP looks like this : ``` function my_test_action() { $var = "this is a test"; wp_send_json($var); die(); } add_action( 'wp_ajax_my_test_action', 'my_test_action' ); add_action( 'wp_ajax_nopriv_my_test_action', 'my_test_action' ); ``` I've also tried : `echo json_encode($var)` or `echo $var`, instead of `wp_send_json()` but the function always returns 0 in the browser console ! My other AJAX calls work, for instance I have another one that calls a PHP script which calls a WP Query and displays some posts, it works fine. **EDIT :** Here is how my script is included : ``` function add_js() { if (is_page_template()) { wp_enqueue_script( 'mycustomscript', get_stylesheet_directory_uri().'/js/mycustomscript.js', array('jquery'), '1.0', true ); wp_localize_script('mycustomscript', 'ajaxurl', admin_url( 'admin-ajax.php' ) ); } } add_action('wp_enqueue_scripts', 'add_js'); ``` I think the problem comes from the `newFormChange` variable, because `jQuery(this).serialize();` didn't work in the first place, because the form is not submitted but only one of its fields changes. So I replaced it by var `newFormChange = jQuery("#term").val();` but then maybe there is a problem with `url: "/wp-admin/admin-ajax.php"` Where am I mistaken ? Thanks
Note that the `action` should be inside the `data` key. In your post request there is no key named as `action` therefore, the callback function is never being called. Consider this example:- ``` jQuery.ajax({ type:"POST", url: "/wp-admin/admin-ajax.php", data: { action: "my_test_action", form_data : newFormChange }, success: function (data) { console.log(data); } }); ``` **Also Note:** Never use relative Ajax URL like `/wp-admin/admin-ajax.php`. You can use [`wp_localize_script()`](https://codex.wordpress.org/Function_Reference/wp_localize_script). See these [examples](https://codex.wordpress.org/AJAX_in_Plugins)
225,102
<p>I've tried to look for a specific answer/tutorial on this subject but I'm coming up short and wanted to see what the SE community could suggest. At this point, any guidance whatsoever would be most appreciated. </p> <p>Basically I'm trying to determine the current page being viewed within a class method I'm setting up, but I haven't had any luck so far. <em>The idea is to enqueue scripts/styles if the appropriate conditions are met: Feature is enabled and set to all pages, or feature enabled and set to display on the current page being viewed.</em></p> <p>Here is the latest version of the code I've been working on:</p> <pre><code>&lt;?php if( !class_exists('CTA_Modal') ) { Class CTA_Modal { public $current_post; public function __construct($post_id) { $this-&gt;current_post = $post_id; // $this-&gt;load_feature(); } public function load_feature() { $modal_display = array( 'enabled' =&gt; true, 'all_pages' =&gt; true, 'pages' =&gt; array() ); $modal_display['enabled'] = get_field('ctamodal_enabled', 'options'); $modal_display['all_pages'] = get_field('ctamodal_show_all', 'options'); $modal_display['pages'] = ( $modal_display['all_pages'] ) ? array() : get_field('ctamodal_show_pages', 'options'); if( $modal_display['enabled'] ) { if( $modal_display['all_pages'] ) { add_action( 'wp_enqueue_scripts', array($this, 'enqueue') ); } else if( !empty($modal_display['pages']) ) { $pages = $modal_display['pages']; foreach ($pages as $page) { if( $page === $this-&gt;current_post ) { add_action( 'wp_enqueue_scripts', array($this, 'enqueue') ); } } } } echo '&lt;!--'; echo $this-&gt;current_post; echo '--&gt;'; } public function enqueue() { $vendor = get_stylesheet_directory_uri() . '/vendor'; wp_enqueue_style('fancybox-css', $vendor . '/fancybox/jquery.fancybox.css'); wp_enqueue_script('fancybox-js', $vendor . '/fancybox/jquery.fancybox.js', array('jquery'), '2.1.5'); } } } </code></pre> <p>I can't seem to figure out why declaring <code>global $post;</code> doesn't have the desired effect either. I was originally declaring the global and reseting the query right in this file (i.e. file the code above lives in) and also in the functions.php file, but I wasn't able to get a different result.</p> <p>Any suggestions/guidance would be most appreciated!</p>
[ { "answer_id": 225109, "author": "sălă", "author_id": 93062, "author_profile": "https://wordpress.stackexchange.com/users/93062", "pm_score": 0, "selected": false, "text": "<p>Have you tried <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow\"><code>get_the_ID</code></a> function?</p>\n\n<p>Try <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow\">this</a> one to get the ID and after that you can get all the info you want. Does it help?</p>\n" }, { "answer_id": 225114, "author": "Ian Svoboda", "author_id": 86773, "author_profile": "https://wordpress.stackexchange.com/users/86773", "pm_score": 2, "selected": true, "text": "<p><a href=\"https://wordpress.stackexchange.com/a/199997/86773\">https://wordpress.stackexchange.com/a/199997/86773</a></p>\n\n<p>As the advice suggested here, switching my hook to \"wp\" instead of \"init\" allowed me to make the page comparison I wanted using is_page(). </p>\n" } ]
2016/04/28
[ "https://wordpress.stackexchange.com/questions/225102", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86773/" ]
I've tried to look for a specific answer/tutorial on this subject but I'm coming up short and wanted to see what the SE community could suggest. At this point, any guidance whatsoever would be most appreciated. Basically I'm trying to determine the current page being viewed within a class method I'm setting up, but I haven't had any luck so far. *The idea is to enqueue scripts/styles if the appropriate conditions are met: Feature is enabled and set to all pages, or feature enabled and set to display on the current page being viewed.* Here is the latest version of the code I've been working on: ``` <?php if( !class_exists('CTA_Modal') ) { Class CTA_Modal { public $current_post; public function __construct($post_id) { $this->current_post = $post_id; // $this->load_feature(); } public function load_feature() { $modal_display = array( 'enabled' => true, 'all_pages' => true, 'pages' => array() ); $modal_display['enabled'] = get_field('ctamodal_enabled', 'options'); $modal_display['all_pages'] = get_field('ctamodal_show_all', 'options'); $modal_display['pages'] = ( $modal_display['all_pages'] ) ? array() : get_field('ctamodal_show_pages', 'options'); if( $modal_display['enabled'] ) { if( $modal_display['all_pages'] ) { add_action( 'wp_enqueue_scripts', array($this, 'enqueue') ); } else if( !empty($modal_display['pages']) ) { $pages = $modal_display['pages']; foreach ($pages as $page) { if( $page === $this->current_post ) { add_action( 'wp_enqueue_scripts', array($this, 'enqueue') ); } } } } echo '<!--'; echo $this->current_post; echo '-->'; } public function enqueue() { $vendor = get_stylesheet_directory_uri() . '/vendor'; wp_enqueue_style('fancybox-css', $vendor . '/fancybox/jquery.fancybox.css'); wp_enqueue_script('fancybox-js', $vendor . '/fancybox/jquery.fancybox.js', array('jquery'), '2.1.5'); } } } ``` I can't seem to figure out why declaring `global $post;` doesn't have the desired effect either. I was originally declaring the global and reseting the query right in this file (i.e. file the code above lives in) and also in the functions.php file, but I wasn't able to get a different result. Any suggestions/guidance would be most appreciated!
<https://wordpress.stackexchange.com/a/199997/86773> As the advice suggested here, switching my hook to "wp" instead of "init" allowed me to make the page comparison I wanted using is\_page().
225,120
<p>I wish to hide certain posts for anyone that is not logged in. I tried the Restrict Content (RC) plugin but that did only hide the content of posts, i wish to omit the post completely.</p> <p>Using RC as a foundation i tried the following:</p> <pre><code>function hideFromUnknownUsers($postObject) { $rcUserLevel = get_post_meta ( $postObject-&gt;ID, 'rcUserLevel', true ); if(have_posts()) { if (!( !current_user_can ( 'read' ) &amp;&amp; ( $rcUserLevel == 'Administrator' || $rcUserLevel == 'Editor' || $rcUserLevel == 'Author' || $rcUserLevel == 'Contributor' || $rcUserLevel == 'Subscriber' ) )) { the_post(); } } } add_action ( 'the_post', 'hideFromUnknownUsers' ); </code></pre> <p>This has a systematic downside. The last post can not be ignored. I can however live with that for now. Another problem is that this also causes an infinite loop, repeating the same posts over and over again. I found that this is because the <code>have_posts()</code> does not only tell us that the end of the last post has been reached but has the side effect that the post counter is also reset preventing my main loop from reaching its end. Making a <code>have_posts()</code> that are non invasive proved difficult since i could not figure out how to reach the <code>$wp_query-&gt;current_post</code>and <code>$wp_query-&gt;post_count</code> from the plugin.</p> <p>One solution would be having the above logic directly in the themes PHP files but that would have to be repeated everywhere i intend to access a post making it cumbersome and prone to errors.</p> <p>Is there any other way to hide certain posts from unknown users?</p>
[ { "answer_id": 225109, "author": "sălă", "author_id": 93062, "author_profile": "https://wordpress.stackexchange.com/users/93062", "pm_score": 0, "selected": false, "text": "<p>Have you tried <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow\"><code>get_the_ID</code></a> function?</p>\n\n<p>Try <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow\">this</a> one to get the ID and after that you can get all the info you want. Does it help?</p>\n" }, { "answer_id": 225114, "author": "Ian Svoboda", "author_id": 86773, "author_profile": "https://wordpress.stackexchange.com/users/86773", "pm_score": 2, "selected": true, "text": "<p><a href=\"https://wordpress.stackexchange.com/a/199997/86773\">https://wordpress.stackexchange.com/a/199997/86773</a></p>\n\n<p>As the advice suggested here, switching my hook to \"wp\" instead of \"init\" allowed me to make the page comparison I wanted using is_page(). </p>\n" } ]
2016/04/28
[ "https://wordpress.stackexchange.com/questions/225120", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93182/" ]
I wish to hide certain posts for anyone that is not logged in. I tried the Restrict Content (RC) plugin but that did only hide the content of posts, i wish to omit the post completely. Using RC as a foundation i tried the following: ``` function hideFromUnknownUsers($postObject) { $rcUserLevel = get_post_meta ( $postObject->ID, 'rcUserLevel', true ); if(have_posts()) { if (!( !current_user_can ( 'read' ) && ( $rcUserLevel == 'Administrator' || $rcUserLevel == 'Editor' || $rcUserLevel == 'Author' || $rcUserLevel == 'Contributor' || $rcUserLevel == 'Subscriber' ) )) { the_post(); } } } add_action ( 'the_post', 'hideFromUnknownUsers' ); ``` This has a systematic downside. The last post can not be ignored. I can however live with that for now. Another problem is that this also causes an infinite loop, repeating the same posts over and over again. I found that this is because the `have_posts()` does not only tell us that the end of the last post has been reached but has the side effect that the post counter is also reset preventing my main loop from reaching its end. Making a `have_posts()` that are non invasive proved difficult since i could not figure out how to reach the `$wp_query->current_post`and `$wp_query->post_count` from the plugin. One solution would be having the above logic directly in the themes PHP files but that would have to be repeated everywhere i intend to access a post making it cumbersome and prone to errors. Is there any other way to hide certain posts from unknown users?
<https://wordpress.stackexchange.com/a/199997/86773> As the advice suggested here, switching my hook to "wp" instead of "init" allowed me to make the page comparison I wanted using is\_page().
225,124
<p>I've built a site for a client, only ten pages, nothing especially big, and created a role for the group members called Blogger, as the staff need to all be able to both blog and access a couple of plugins (for a client carousel and to add testimonials). I disabled their ability to edit pages using a plugin called Adminimise as I didn't really want to give them that access and possibly break anything by mistake.</p> <p>OK - All is well so far? This is where I've discovered Adminimise falls short slightly. What my client requires is that just one page - a page called Trustees - is editable by them so they can add names to an on-going list as required.</p> <p>How can I make an individual page editable by a non-administrative role whilst keeping the others disabled? I'm praying this is possible, but am not getting very far with Google and have hit a bit of a wall.</p>
[ { "answer_id": 225126, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 0, "selected": false, "text": "<p>Adminimize does not <strong>remove</strong> menu items etc, it just keeps them <strong>visually hidden</strong>. In other words, your admin pages is still accessible.</p>\n\n<p>Add this code to your <code>functions.php</code> file:</p>\n\n<pre><code>add_action('admin_menu', 'edit_trustees_page');\nfunction edit_trustees_page() {\n global $submenu;\n $trustees_page_id = 1; //change this value\n $url = get_admin_url() . 'post.php?post=' . $trustees_page_id . '&amp;action=edit';\n $submenu['index.php'][] = array( 'Edit Trustees', 'manage_options', $url ); // replace manage_options with your custom role\n}\n</code></pre>\n\n<p>It will add a new submenu to <code>Dashboard</code>. You can change <code>index.php</code> to any of these:</p>\n\n<pre><code>index.php =&gt; Dashboard\nedit.php =&gt; Posts\nupload.php =&gt; Media\nlink-manager.php =&gt; Links\nedit.php?post_type=page =&gt; Pages\nedit-comments.php =&gt; Comments\nthemes.php =&gt; Appearance\nplugins.php =&gt; Plugins\nusers.php =&gt; Users\ntools.php =&gt; Tools\noptions-general.php =&gt; Settings\n</code></pre>\n" }, { "answer_id": 225630, "author": "Andy Woggle", "author_id": 93190, "author_profile": "https://wordpress.stackexchange.com/users/93190", "pm_score": -1, "selected": false, "text": "<p>RESOLVED!! It was me missing a trick within Role Scoper. All sorted!</p>\n\n<p>Thanks Mukto90 and Monkey Puzzle for your input. </p>\n\n<p>Cheers!</p>\n\n<p>Andy</p>\n" } ]
2016/04/28
[ "https://wordpress.stackexchange.com/questions/225124", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93190/" ]
I've built a site for a client, only ten pages, nothing especially big, and created a role for the group members called Blogger, as the staff need to all be able to both blog and access a couple of plugins (for a client carousel and to add testimonials). I disabled their ability to edit pages using a plugin called Adminimise as I didn't really want to give them that access and possibly break anything by mistake. OK - All is well so far? This is where I've discovered Adminimise falls short slightly. What my client requires is that just one page - a page called Trustees - is editable by them so they can add names to an on-going list as required. How can I make an individual page editable by a non-administrative role whilst keeping the others disabled? I'm praying this is possible, but am not getting very far with Google and have hit a bit of a wall.
Adminimize does not **remove** menu items etc, it just keeps them **visually hidden**. In other words, your admin pages is still accessible. Add this code to your `functions.php` file: ``` add_action('admin_menu', 'edit_trustees_page'); function edit_trustees_page() { global $submenu; $trustees_page_id = 1; //change this value $url = get_admin_url() . 'post.php?post=' . $trustees_page_id . '&action=edit'; $submenu['index.php'][] = array( 'Edit Trustees', 'manage_options', $url ); // replace manage_options with your custom role } ``` It will add a new submenu to `Dashboard`. You can change `index.php` to any of these: ``` index.php => Dashboard edit.php => Posts upload.php => Media link-manager.php => Links edit.php?post_type=page => Pages edit-comments.php => Comments themes.php => Appearance plugins.php => Plugins users.php => Users tools.php => Tools options-general.php => Settings ```
225,152
<h2>Question</h2> <p>Is there a way to remove a specific shortcode, say <code>[print_me]</code> from all the posts where it appears in one shot. And I don't mean mask it or filter it so it doesn't show up while it stays in the <code>post_content</code>. I want it GONE GONE.</p> <h2>Attempts So Far ...</h2> <p>So far what I have done is using phpMyAdmin, I ran a query on all <code>post_content</code> that appears in the table <code>wp_posts</code> and it shows all the posts that I was looking for but there is too many to handle individually. I ran a find/replace update query on the results trying to replace it with <code>""</code> (nothing) but while the query ran successfully, so it said, I don't see the shortcodes gone, so I am not sure if I missed something.</p> <p>Here is the query I used to find them:</p> <pre><code>SELECT * FROM `wp_posts` WHERE `post_content` LIKE '%[print_me]%' </code></pre> <p>and I get 111 records. But then using the same tool to do a search and replace, I get:</p> <blockquote> <p><strong>Your SQL query has been executed successfully</strong></p> <p>UPDATE <code>db1357924680</code>.<code>wp_posts</code> SET <code>post_content</code> = REPLACE(<code>post_content</code>, '%[print_me]%', '%%') WHERE <code>post_content</code> LIKE '%%[print_me]%%' COLLATE utf8_bin</p> </blockquote> <p>But when you check, they are all still there. SO I am hoping someone knows a better or proper way of doing this and willing to share. If I am on the right track, then I would appreciate some assistance in figuring out why its not working as expected. TIA.</p> <h2>Resolution (thanks to @TheDeadMedic)</h2> <p>Using the corrections to my original SQL query (as follows and found in the original answer), it worked flawlessly and I accomplished what I needed, thank you.</p> <blockquote> <p>UPDATE db1357924680.wp_posts SET post_content = REPLACE( post_content, '[print_me]', '' ) WHERE post_content LIKE '%[print_me]%'</p> </blockquote> <hr> <h2>History (tl/rl)</h2> <p>I had been using a plugin for a while now that can make something appear on EVERY post and page or you could opt to only put the shortcode when you felt it was appropriate for that content.</p> <p>However, after about 2 years, I gave it up in favor of a more wholesale solution that provided some other features that I wanted to incorporate in addition.</p> <p>I have deactivated the plugin but now facing the problem of those shortcodes printing out as regular old text and that's something I need to resolve.</p> <p>Some environment/system information: <strong>PHP/Linux/WP_4.5.1/SQL_5.1.73/PMA_4.1.14.8</strong></p>
[ { "answer_id": 225156, "author": "Frits", "author_id": 93169, "author_profile": "https://wordpress.stackexchange.com/users/93169", "pm_score": 3, "selected": false, "text": "<p>There is an easier way to do this:</p>\n\n<pre><code>add_filter( 'the_content', 'my_post_content_remove_shortcodes', 0 );\n\nfunction my_post_content_remove_shortcodes( $content ) {\n\n /* Create an array of all the shortcode tags. */\n $shortcode_tags = array(\n 'shortcode_1',\n 'shortcode_2',\n 'shortcode_3'\n );\n\n /* Loop through the shortcodes and remove them. */\n foreach ( $shortcode_tags as $shortcode_tag )\n remove_shortcode( $shortcode_tag );\n\n /* Return the post content. */\n return $content;\n}\n</code></pre>\n\n<p>You can drop this in to your functions file. </p>\n\n<p>Source: <a href=\"http://justintadlock.com/archives/2013/01/08/disallow-specific-shortcodes-in-post-content\" rel=\"noreferrer\">http://justintadlock.com/archives/2013/01/08/disallow-specific-shortcodes-in-post-content</a></p>\n\n<p>--edit--</p>\n\n<p>Instead of searching through your MySQL entries to remove everything, you can \"remove\" the shortcode's functionality through your functions file.</p>\n\n<p>The code below will filter through all of your content and remove specific shortcodes that you designate in the place marked as <code>shortcode_1</code> etc.</p>\n\n<p>As Mark said: This is not quite what you asked for but will give you similar results if you struggle to find something else.</p>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 225175, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 4, "selected": true, "text": "<p>For the permanent solution, your SQL query is slightly off - you need:</p>\n\n<pre><code>UPDATE db1357924680.wp_posts SET post_content = REPLACE( post_content, '[print_me]', '' ) WHERE post_content LIKE '%[print_me]%' \n</code></pre>\n\n<p><a href=\"https://techjourney.net/how-to-find-and-replace-text-in-mysql-database-using-sql/\">MySQL replace example</a></p>\n" } ]
2016/04/29
[ "https://wordpress.stackexchange.com/questions/225152", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37180/" ]
Question -------- Is there a way to remove a specific shortcode, say `[print_me]` from all the posts where it appears in one shot. And I don't mean mask it or filter it so it doesn't show up while it stays in the `post_content`. I want it GONE GONE. Attempts So Far ... ------------------- So far what I have done is using phpMyAdmin, I ran a query on all `post_content` that appears in the table `wp_posts` and it shows all the posts that I was looking for but there is too many to handle individually. I ran a find/replace update query on the results trying to replace it with `""` (nothing) but while the query ran successfully, so it said, I don't see the shortcodes gone, so I am not sure if I missed something. Here is the query I used to find them: ``` SELECT * FROM `wp_posts` WHERE `post_content` LIKE '%[print_me]%' ``` and I get 111 records. But then using the same tool to do a search and replace, I get: > > **Your SQL query has been executed successfully** > > > UPDATE `db1357924680`.`wp_posts` SET `post_content` = REPLACE(`post_content`, > '%[print\_me]%', '%%') WHERE `post_content` LIKE '%%[print\_me]%%' > COLLATE utf8\_bin > > > But when you check, they are all still there. SO I am hoping someone knows a better or proper way of doing this and willing to share. If I am on the right track, then I would appreciate some assistance in figuring out why its not working as expected. TIA. Resolution (thanks to @TheDeadMedic) ------------------------------------ Using the corrections to my original SQL query (as follows and found in the original answer), it worked flawlessly and I accomplished what I needed, thank you. > > UPDATE db1357924680.wp\_posts SET post\_content = REPLACE( post\_content, > '[print\_me]', '' ) WHERE post\_content LIKE '%[print\_me]%' > > > --- History (tl/rl) --------------- I had been using a plugin for a while now that can make something appear on EVERY post and page or you could opt to only put the shortcode when you felt it was appropriate for that content. However, after about 2 years, I gave it up in favor of a more wholesale solution that provided some other features that I wanted to incorporate in addition. I have deactivated the plugin but now facing the problem of those shortcodes printing out as regular old text and that's something I need to resolve. Some environment/system information: **PHP/Linux/WP\_4.5.1/SQL\_5.1.73/PMA\_4.1.14.8**
For the permanent solution, your SQL query is slightly off - you need: ``` UPDATE db1357924680.wp_posts SET post_content = REPLACE( post_content, '[print_me]', '' ) WHERE post_content LIKE '%[print_me]%' ``` [MySQL replace example](https://techjourney.net/how-to-find-and-replace-text-in-mysql-database-using-sql/)
225,171
<p>I am inserting data in the custom table using the <code>$wpdb-&gt;insert</code>. However, upon error I don't seem to get any information from <code>$wpdb-&gt;last_error</code>. What could be the cause of this?</p> <p>I already have this configuration set in <code>wp-config</code></p> <pre><code>define('WP_DEBUG', false); define('SAVEQUERIES', true); </code></pre> <p>The code is as below:</p> <pre><code>$result = $wpdb-&gt;insert($this-&gt;table, $data_); if (false === $result) { error_log($wpdb-&gt;last_error); } </code></pre> <p><code>$this-&gt;table</code> and <code>$data_</code> are populated correctly as it runs successfully. But I don't seem to get any information on the query that is failed. Is there any way I can get the actual query ran in <code>$wpdb-&gt;insert</code>?</p> <p><strong>Solution</strong></p> <p>OK so I figured out the problem. Insert query was failing because one of the column data was huge and exceeding the column size of the database. The column was <code>varchar(500)</code> but the actual data was more then 500 characters, thus failing the query. I changed the column to <code>TEXT</code> and insert was successful without errors.</p>
[ { "answer_id": 225174, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 3, "selected": false, "text": "<p>If you want the <em>query</em>, that'll be <code>$wpdb-&gt;last_query</code> (note that you also do not need <code>SAVEQUERIES</code>, that's only if you want a log of <em>every</em> query (<code>$wpdb-&gt;queries</code>)</p>\n\n<p><code>last_error</code> is... well, the error!</p>\n\n<p><strong>Update:</strong> Possible explanation for <code>last_error</code> being empty - this is the source of <code>wpdb::query()</code>:</p>\n\n<pre><code>// If we're writing to the database, make sure the query will write safely.\nif ( $this-&gt;check_current_query &amp;&amp; ! $this-&gt;check_ascii( $query ) ) {\n $stripped_query = $this-&gt;strip_invalid_text_from_query( $query );\n // strip_invalid_text_from_query() can perform queries, so we need\n // to flush again, just to make sure everything is clear.\n $this-&gt;flush();\n if ( $stripped_query !== $query ) {\n $this-&gt;insert_id = 0;\n return false;\n }\n}\n\n// Redacted code\n\n// Keep track of the last query for debug..\n$this-&gt;last_query = $query;\n\n$this-&gt;_do_query( $query );\n\n// Redacted code\n\n// If there is an error then take note of it..\nif ( $this-&gt;use_mysqli ) {\n $this-&gt;last_error = mysqli_error( $this-&gt;dbh );\n} else {\n $this-&gt;last_error = mysql_error( $this-&gt;dbh );\n}\n</code></pre>\n\n<p>In other words, WordPress seems to pre-emptively check the query and will abort if it deems it will fail - in this case you get your <code>return false</code> but no error will be set (since it was never sent to the MySQL server).</p>\n" }, { "answer_id": 225176, "author": "user5200704", "author_id": 92477, "author_profile": "https://wordpress.stackexchange.com/users/92477", "pm_score": 1, "selected": false, "text": "<p>try this</p>\n\n<pre><code>$wpdb-&gt;show_errors();\n$result = $wpdb-&gt;insert($this-&gt;table, $data_);\n</code></pre>\n" }, { "answer_id": 331206, "author": "Liam Mitchell", "author_id": 147059, "author_profile": "https://wordpress.stackexchange.com/users/147059", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://core.trac.wordpress.org/ticket/32315\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/32315</a></p>\n\n<p>One of the columns inputs may be larger than the column is.\nWordpress detects this and will not even send the query to the DB.</p>\n\n<p>The Diff there shows a patch for wp-db you can put in to get more information in the last_error message so it will not be empty.</p>\n\n<p><a href=\"https://i.stack.imgur.com/plQYS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/plQYS.png\" alt=\"enter image description here\"></a></p>\n" } ]
2016/04/29
[ "https://wordpress.stackexchange.com/questions/225171", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22857/" ]
I am inserting data in the custom table using the `$wpdb->insert`. However, upon error I don't seem to get any information from `$wpdb->last_error`. What could be the cause of this? I already have this configuration set in `wp-config` ``` define('WP_DEBUG', false); define('SAVEQUERIES', true); ``` The code is as below: ``` $result = $wpdb->insert($this->table, $data_); if (false === $result) { error_log($wpdb->last_error); } ``` `$this->table` and `$data_` are populated correctly as it runs successfully. But I don't seem to get any information on the query that is failed. Is there any way I can get the actual query ran in `$wpdb->insert`? **Solution** OK so I figured out the problem. Insert query was failing because one of the column data was huge and exceeding the column size of the database. The column was `varchar(500)` but the actual data was more then 500 characters, thus failing the query. I changed the column to `TEXT` and insert was successful without errors.
If you want the *query*, that'll be `$wpdb->last_query` (note that you also do not need `SAVEQUERIES`, that's only if you want a log of *every* query (`$wpdb->queries`) `last_error` is... well, the error! **Update:** Possible explanation for `last_error` being empty - this is the source of `wpdb::query()`: ``` // If we're writing to the database, make sure the query will write safely. if ( $this->check_current_query && ! $this->check_ascii( $query ) ) { $stripped_query = $this->strip_invalid_text_from_query( $query ); // strip_invalid_text_from_query() can perform queries, so we need // to flush again, just to make sure everything is clear. $this->flush(); if ( $stripped_query !== $query ) { $this->insert_id = 0; return false; } } // Redacted code // Keep track of the last query for debug.. $this->last_query = $query; $this->_do_query( $query ); // Redacted code // If there is an error then take note of it.. if ( $this->use_mysqli ) { $this->last_error = mysqli_error( $this->dbh ); } else { $this->last_error = mysql_error( $this->dbh ); } ``` In other words, WordPress seems to pre-emptively check the query and will abort if it deems it will fail - in this case you get your `return false` but no error will be set (since it was never sent to the MySQL server).
225,182
<p>Sorry, I know this kind of question has been asked before but I can't quite figure it out. </p> <p>I'm trying to hide the city image on this page:</p> <p><a href="http://learnenglish20.com/buy-tokens/" rel="nofollow">http://learnenglish20.com/buy-tokens/</a></p> <p>I put this CSS in my child theme: </p> <pre><code> body.page-id-2557 #title-content { display: none !important; </code></pre> <p>}</p> <p>I think maybe I've got my class wrong? Anyway, I'd really appreciate any help </p>
[ { "answer_id": 225183, "author": "tam", "author_id": 18668, "author_profile": "https://wordpress.stackexchange.com/users/18668", "pm_score": 1, "selected": false, "text": "<p>Just override the background property with the below code in your child css.</p>\n\n<pre><code>#title {\n background: none !important;\n}\n</code></pre>\n" }, { "answer_id": 225184, "author": "Howard E", "author_id": 57589, "author_profile": "https://wordpress.stackexchange.com/users/57589", "pm_score": 1, "selected": false, "text": "<p>It should look like this:</p>\n\n<pre><code>.page-id-2557 section#title {\n background: none !important;\n}\n</code></pre>\n\n<p>This removes the image, then you may want to change the color of the title</p>\n\n<p>Which you'd have to also use !important, since this theme uses !important a lot, which isn't great... try to avoid.</p>\n\n<pre><code>.page-id-2557 #title.title-area .title-content .title-text h1 {\n color: #FFA23B !important;\n}\n</code></pre>\n" }, { "answer_id": 225185, "author": "Tazz M", "author_id": 93231, "author_profile": "https://wordpress.stackexchange.com/users/93231", "pm_score": 0, "selected": false, "text": "<p>It seems you want to hide the logo image that's displayed instead of the site title. Check the image element in source code and then add the custom class to the specific element. </p>\n\n<p>A second option would be to create a custom page template, and then use it while publishing that particular page. </p>\n" }, { "answer_id": 225193, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 0, "selected": false, "text": "<p>You could use <code>background-position</code> and just move it out of the view of the element.</p>\n\n<pre><code>element.class{\n background-position:-9999px;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>element.class{\n background:transparent;\n}\n</code></pre>\n" } ]
2016/04/29
[ "https://wordpress.stackexchange.com/questions/225182", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93230/" ]
Sorry, I know this kind of question has been asked before but I can't quite figure it out. I'm trying to hide the city image on this page: <http://learnenglish20.com/buy-tokens/> I put this CSS in my child theme: ``` body.page-id-2557 #title-content { display: none !important; ``` } I think maybe I've got my class wrong? Anyway, I'd really appreciate any help
Just override the background property with the below code in your child css. ``` #title { background: none !important; } ```
225,203
<p>Could use some help... using this code to call up a custom number of posts from a certain categorey and only want to display the first 15 characters. However, it is showing the same excerpt on each post versus showing the unique excerpt for each post. Can anyone help me out on this one? </p> <p>Code below is resulting in the same excerpt to be added to the posts, even though the correct title and thumbnails are displaying!</p> <p>I'm a bit of a novice so if you can explain I'd gladly appreciate it!</p> <pre><code>&lt;?php $posts = get_posts('category=3&amp;orderby=date&amp;numberposts=3'); foreach($posts as $post) { ?&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" target="_parent"&gt; &lt;div class="aligncenter" style="display: block;"&gt; &lt;?php the_post_thumbnail( 'thumbnail', array( 'class' =&gt; 'img-responsive' ) ); ?&gt; &lt;/div&gt; &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt;&lt;/a&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;?php echo excerpt(15); ?&gt; &lt;?php endwhile; ?&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" class="blue"" target="_parent"&gt; Read More&lt;/a&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>here is my functions.php</p> <pre><code>function excerpt($limit) { $excerpt = explode(' ', get_the_excerpt(), $limit); if (count($excerpt)&gt;=$limit) { array_pop($excerpt); $excerpt = implode(" ",$excerpt).'...'; } else { $excerpt = implode(" ",$excerpt); } $excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt); return $excerpt; } function content($limit) { $content = explode(' ', get_the_content(), $limit); if (count($content)&gt;=$limit) { array_pop($content); $content = implode(" ",$content).'...'; } else { $content = implode(" ",$content); } $content = preg_replace('/\[.+\]/','', $content); $content = apply_filters('the_content', $content); $content = str_replace(']]&gt;', ']]&amp;gt;', $content); return $content; </code></pre>
[ { "answer_id": 225183, "author": "tam", "author_id": 18668, "author_profile": "https://wordpress.stackexchange.com/users/18668", "pm_score": 1, "selected": false, "text": "<p>Just override the background property with the below code in your child css.</p>\n\n<pre><code>#title {\n background: none !important;\n}\n</code></pre>\n" }, { "answer_id": 225184, "author": "Howard E", "author_id": 57589, "author_profile": "https://wordpress.stackexchange.com/users/57589", "pm_score": 1, "selected": false, "text": "<p>It should look like this:</p>\n\n<pre><code>.page-id-2557 section#title {\n background: none !important;\n}\n</code></pre>\n\n<p>This removes the image, then you may want to change the color of the title</p>\n\n<p>Which you'd have to also use !important, since this theme uses !important a lot, which isn't great... try to avoid.</p>\n\n<pre><code>.page-id-2557 #title.title-area .title-content .title-text h1 {\n color: #FFA23B !important;\n}\n</code></pre>\n" }, { "answer_id": 225185, "author": "Tazz M", "author_id": 93231, "author_profile": "https://wordpress.stackexchange.com/users/93231", "pm_score": 0, "selected": false, "text": "<p>It seems you want to hide the logo image that's displayed instead of the site title. Check the image element in source code and then add the custom class to the specific element. </p>\n\n<p>A second option would be to create a custom page template, and then use it while publishing that particular page. </p>\n" }, { "answer_id": 225193, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 0, "selected": false, "text": "<p>You could use <code>background-position</code> and just move it out of the view of the element.</p>\n\n<pre><code>element.class{\n background-position:-9999px;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>element.class{\n background:transparent;\n}\n</code></pre>\n" } ]
2016/04/29
[ "https://wordpress.stackexchange.com/questions/225203", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85626/" ]
Could use some help... using this code to call up a custom number of posts from a certain categorey and only want to display the first 15 characters. However, it is showing the same excerpt on each post versus showing the unique excerpt for each post. Can anyone help me out on this one? Code below is resulting in the same excerpt to be added to the posts, even though the correct title and thumbnails are displaying! I'm a bit of a novice so if you can explain I'd gladly appreciate it! ``` <?php $posts = get_posts('category=3&orderby=date&numberposts=3'); foreach($posts as $post) { ?> <a href="<?php the_permalink() ?>" target="_parent"> <div class="aligncenter" style="display: block;"> <?php the_post_thumbnail( 'thumbnail', array( 'class' => 'img-responsive' ) ); ?> </div> <h3><?php the_title(); ?></h3></a> <?php while (have_posts()) : the_post(); ?> <?php echo excerpt(15); ?> <?php endwhile; ?> <a href="<?php the_permalink() ?>" class="blue"" target="_parent"> Read More</a> </div> <?php } ?> ``` here is my functions.php ``` function excerpt($limit) { $excerpt = explode(' ', get_the_excerpt(), $limit); if (count($excerpt)>=$limit) { array_pop($excerpt); $excerpt = implode(" ",$excerpt).'...'; } else { $excerpt = implode(" ",$excerpt); } $excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt); return $excerpt; } function content($limit) { $content = explode(' ', get_the_content(), $limit); if (count($content)>=$limit) { array_pop($content); $content = implode(" ",$content).'...'; } else { $content = implode(" ",$content); } $content = preg_replace('/\[.+\]/','', $content); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]&gt;', $content); return $content; ```
Just override the background property with the below code in your child css. ``` #title { background: none !important; } ```
225,208
<p>I have a custom user database that is integrated with a wordpress website using a custom built plugin. I also want to integrate this user system into the comment system.</p> <p>I have found and completed the code that will handle comment submissions and reject bad ones, but i cannot find out how to actually override the visual side of things. All comment plugins i have used visually change the comment submission form, but i cant find any tutorials on it. </p>
[ { "answer_id": 225210, "author": "tam", "author_id": 18668, "author_profile": "https://wordpress.stackexchange.com/users/18668", "pm_score": 0, "selected": false, "text": "<p>I believe you can hook your new function to <code>comment_template()</code> like this:</p>\n\n<pre><code>add_action('comments_template', 'my_function')\n</code></pre>\n\n<p>or </p>\n\n<pre><code>function hide_my_comment_template() {\n return null;\n}\nadd_action('comments_template', 'hide_my_comment_template')\n</code></pre>\n" }, { "answer_id": 225262, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 2, "selected": false, "text": "<p>Now what if you have to add/remove fields from default contact form to change the feel of your comment box? I am eliminating website field from default comment box by playing with ‘fields’ argument:in comments.php</p>\n\n<pre><code>&lt;?php $comment_args = array('title_reply' =&gt; 'Got Something To Say:',\n 'fields' =&gt; apply_filters('comment_form_default_fields', array(\n 'author' =&gt; '&lt;p class=\"comment-form-author\"&gt;' . '&lt;label for=\"author\"&gt;' . __('Your Good Name') . '&lt;/label&gt; ' . ($req ? '&lt;span&gt;*&lt;/span&gt;' : '') .\n '&lt;input id=\"author\" name=\"author\" type=\"text\" value=\"' . esc_attr($commenter['comment_author']) . '\" size=\"30\"' . $aria_req . ' /&gt;&lt;/p&gt;',\n 'email' =&gt; '&lt;p class=\"comment-form-email\"&gt;' .\n '&lt;label for=\"email\"&gt;' . __('Your Email Please') . '&lt;/label&gt; ' .\n ($req ? '&lt;span&gt;*&lt;/span&gt;' : '') .\n '&lt;input id=\"email\" name=\"email\" type=\"text\" value=\"' . esc_attr($commenter['comment_author_email']) . '\" size=\"30\"' . $aria_req . ' /&gt;' . '&lt;/p&gt;',\n 'url' =&gt; '')),\n 'comment_field' =&gt; '&lt;p&gt;' .\n '&lt;label for=\"comment\"&gt;' . __('Let us know what you have to say:') . '&lt;/label&gt;' .\n '&lt;textarea id=\"comment\" name=\"comment\" cols=\"45\" rows=\"8\" aria-required=\"true\"&gt;&lt;/textarea&gt;' .\n '&lt;/p&gt;',\n 'comment_notes_after' =&gt; '',\n);\ncomment_form($comment_args); ?&gt;\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/V00pn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/V00pn.png\" alt=\"enter image description here\"></a></p>\n" } ]
2016/04/29
[ "https://wordpress.stackexchange.com/questions/225208", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/190834/" ]
I have a custom user database that is integrated with a wordpress website using a custom built plugin. I also want to integrate this user system into the comment system. I have found and completed the code that will handle comment submissions and reject bad ones, but i cannot find out how to actually override the visual side of things. All comment plugins i have used visually change the comment submission form, but i cant find any tutorials on it.
Now what if you have to add/remove fields from default contact form to change the feel of your comment box? I am eliminating website field from default comment box by playing with ‘fields’ argument:in comments.php ``` <?php $comment_args = array('title_reply' => 'Got Something To Say:', 'fields' => apply_filters('comment_form_default_fields', array( 'author' => '<p class="comment-form-author">' . '<label for="author">' . __('Your Good Name') . '</label> ' . ($req ? '<span>*</span>' : '') . '<input id="author" name="author" type="text" value="' . esc_attr($commenter['comment_author']) . '" size="30"' . $aria_req . ' /></p>', 'email' => '<p class="comment-form-email">' . '<label for="email">' . __('Your Email Please') . '</label> ' . ($req ? '<span>*</span>' : '') . '<input id="email" name="email" type="text" value="' . esc_attr($commenter['comment_author_email']) . '" size="30"' . $aria_req . ' />' . '</p>', 'url' => '')), 'comment_field' => '<p>' . '<label for="comment">' . __('Let us know what you have to say:') . '</label>' . '<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>' . '</p>', 'comment_notes_after' => '', ); comment_form($comment_args); ?> ``` [![enter image description here](https://i.stack.imgur.com/V00pn.png)](https://i.stack.imgur.com/V00pn.png)
225,209
<p>I'm studying the theme "one page" and there is the following code:</p> <pre><code>function onepage_sections() { $sections = array(); $sections['service_section'] = array( 'id' =&gt; 'service_section', 'label' =&gt; __('Service Section', 'one-page'), 'callback' =&gt; 'onepage_service_section', ); $sections['blog_section'] = array( 'id' =&gt; 'blog_section', 'label' =&gt; __('Blog Section', 'one-page'), 'callback' =&gt; 'onepage_blog_section', ); return apply_filters('onepage_sections', $sections); } </code></pre> <p>From what I have read the function <code>apply_filters</code> creates a tag (a key name that can be accessed later) and a content that will be susceptible to change whenever someone uses <code>add_filter(key_name, function_to_alter_content_in_key_name)</code>. Correct?</p> <p>What I don't get is that in this theme, there are no calls to add_filter('onepage_sections'). It is simply declared in the preceding call to <code>apply_filters</code>. Could someone clarify the concept of these functions?</p>
[ { "answer_id": 225210, "author": "tam", "author_id": 18668, "author_profile": "https://wordpress.stackexchange.com/users/18668", "pm_score": 0, "selected": false, "text": "<p>I believe you can hook your new function to <code>comment_template()</code> like this:</p>\n\n<pre><code>add_action('comments_template', 'my_function')\n</code></pre>\n\n<p>or </p>\n\n<pre><code>function hide_my_comment_template() {\n return null;\n}\nadd_action('comments_template', 'hide_my_comment_template')\n</code></pre>\n" }, { "answer_id": 225262, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 2, "selected": false, "text": "<p>Now what if you have to add/remove fields from default contact form to change the feel of your comment box? I am eliminating website field from default comment box by playing with ‘fields’ argument:in comments.php</p>\n\n<pre><code>&lt;?php $comment_args = array('title_reply' =&gt; 'Got Something To Say:',\n 'fields' =&gt; apply_filters('comment_form_default_fields', array(\n 'author' =&gt; '&lt;p class=\"comment-form-author\"&gt;' . '&lt;label for=\"author\"&gt;' . __('Your Good Name') . '&lt;/label&gt; ' . ($req ? '&lt;span&gt;*&lt;/span&gt;' : '') .\n '&lt;input id=\"author\" name=\"author\" type=\"text\" value=\"' . esc_attr($commenter['comment_author']) . '\" size=\"30\"' . $aria_req . ' /&gt;&lt;/p&gt;',\n 'email' =&gt; '&lt;p class=\"comment-form-email\"&gt;' .\n '&lt;label for=\"email\"&gt;' . __('Your Email Please') . '&lt;/label&gt; ' .\n ($req ? '&lt;span&gt;*&lt;/span&gt;' : '') .\n '&lt;input id=\"email\" name=\"email\" type=\"text\" value=\"' . esc_attr($commenter['comment_author_email']) . '\" size=\"30\"' . $aria_req . ' /&gt;' . '&lt;/p&gt;',\n 'url' =&gt; '')),\n 'comment_field' =&gt; '&lt;p&gt;' .\n '&lt;label for=\"comment\"&gt;' . __('Let us know what you have to say:') . '&lt;/label&gt;' .\n '&lt;textarea id=\"comment\" name=\"comment\" cols=\"45\" rows=\"8\" aria-required=\"true\"&gt;&lt;/textarea&gt;' .\n '&lt;/p&gt;',\n 'comment_notes_after' =&gt; '',\n);\ncomment_form($comment_args); ?&gt;\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/V00pn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/V00pn.png\" alt=\"enter image description here\"></a></p>\n" } ]
2016/04/29
[ "https://wordpress.stackexchange.com/questions/225209", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92028/" ]
I'm studying the theme "one page" and there is the following code: ``` function onepage_sections() { $sections = array(); $sections['service_section'] = array( 'id' => 'service_section', 'label' => __('Service Section', 'one-page'), 'callback' => 'onepage_service_section', ); $sections['blog_section'] = array( 'id' => 'blog_section', 'label' => __('Blog Section', 'one-page'), 'callback' => 'onepage_blog_section', ); return apply_filters('onepage_sections', $sections); } ``` From what I have read the function `apply_filters` creates a tag (a key name that can be accessed later) and a content that will be susceptible to change whenever someone uses `add_filter(key_name, function_to_alter_content_in_key_name)`. Correct? What I don't get is that in this theme, there are no calls to add\_filter('onepage\_sections'). It is simply declared in the preceding call to `apply_filters`. Could someone clarify the concept of these functions?
Now what if you have to add/remove fields from default contact form to change the feel of your comment box? I am eliminating website field from default comment box by playing with ‘fields’ argument:in comments.php ``` <?php $comment_args = array('title_reply' => 'Got Something To Say:', 'fields' => apply_filters('comment_form_default_fields', array( 'author' => '<p class="comment-form-author">' . '<label for="author">' . __('Your Good Name') . '</label> ' . ($req ? '<span>*</span>' : '') . '<input id="author" name="author" type="text" value="' . esc_attr($commenter['comment_author']) . '" size="30"' . $aria_req . ' /></p>', 'email' => '<p class="comment-form-email">' . '<label for="email">' . __('Your Email Please') . '</label> ' . ($req ? '<span>*</span>' : '') . '<input id="email" name="email" type="text" value="' . esc_attr($commenter['comment_author_email']) . '" size="30"' . $aria_req . ' />' . '</p>', 'url' => '')), 'comment_field' => '<p>' . '<label for="comment">' . __('Let us know what you have to say:') . '</label>' . '<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>' . '</p>', 'comment_notes_after' => '', ); comment_form($comment_args); ?> ``` [![enter image description here](https://i.stack.imgur.com/V00pn.png)](https://i.stack.imgur.com/V00pn.png)
225,280
<p>I need to create a simple plugin to show a list of categories inside the body of the post and, as I am new to coding, I searched for the basics and started to make little changes; it looks like this, by now:</p> <pre><code>// [cats] function catting ( $atts, $content = null ) { global $post; $categories = get_the_category_list( ', ', '', $post-&gt;ID ); return '&lt;div id="cats" class="catting"&gt;' . $categories . '&lt;/div&gt;'; } add_shortcode("cats", "catting"); </code></pre> <p>It shows the categories of a post listed simply and I managed to apply some custom styles on it in order to show it as buttons, but the style is being applied to the shortcode as a whole instead of affecting the categories separate and individually.</p> <p>I am trying to use <code>foreach</code> and to change the commas into a blank space between them, but, every time I try something, it breaks the code or it does not change anything at all.</p> <p>I would like to know the way to apply the style in each category separately and I thank you very much in advance for the help.</p>
[ { "answer_id": 225285, "author": "Usce", "author_id": 81451, "author_profile": "https://wordpress.stackexchange.com/users/81451", "pm_score": -1, "selected": false, "text": "<p>There is build in wordpress function for that , so you can use wp_list_categories() for that. Please refer <a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/\" rel=\"nofollow\">here to learn more</a></p>\n\n<p>And after you display them you an do some CSS if you want to display it as buttons. </p>\n\n<p>I hope this helps. </p>\n\n<p>Kind regards,</p>\n\n<p>Usce</p>\n" }, { "answer_id": 225289, "author": "Jarod Thornton", "author_id": 44017, "author_profile": "https://wordpress.stackexchange.com/users/44017", "pm_score": 1, "selected": true, "text": "<p>I've modified your code to reflect the <code>wp_list_categories()</code> function reference as suggested by @Usce.</p>\n\n<p>This snippet will create an unordered list, remove the \"Categories\" list title, and add the <code>li</code> class with individual category ID so you can target each link in the list. </p>\n\n<p><code>function catting ($atts, $content = null) {\n echo '&lt;div id=\"cats\" class=\"catting\"&gt;' . wp_list_categories('title_li=','current_category') . '&lt;/div&gt;';\n}\nadd_shortcode(\"cats\", \"catting\");</code></p>\n\n<p>Here's some CSS to remove the bullets and margin so it essentially behaves just as your original code but with <code>li</code> wrapping your anchors.</p>\n\n<p>The CSS will break the list we've created into a horizontal line. Just remember to modify your CSS to further customize the outcome i.e. adding styles for buttons. </p>\n\n<p><code>#cats.catting ul {\n display: inline;\n }\n #cats.catting ul li.cat-item {\n list-style: none;\n margin: 0px 10px;\n}</code></p>\n\n<p>I hope this answers your question.</p>\n" }, { "answer_id": 225297, "author": "Alex Black", "author_id": 93298, "author_profile": "https://wordpress.stackexchange.com/users/93298", "pm_score": 0, "selected": false, "text": "<p>Yo don't need to write a plugin for that - what you need already exists. Check this link: <a href=\"https://wordpress.org/plugins/list-categories/\" rel=\"nofollow\">https://wordpress.org/plugins/list-categories/</a>\nWith this plugin you can display categories in any post or page. Of course, maybe you want to write your own plugin, and in that case this link can be helpful.\nI hope that this will help you to speed up a process.</p>\n" } ]
2016/04/30
[ "https://wordpress.stackexchange.com/questions/225280", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93289/" ]
I need to create a simple plugin to show a list of categories inside the body of the post and, as I am new to coding, I searched for the basics and started to make little changes; it looks like this, by now: ``` // [cats] function catting ( $atts, $content = null ) { global $post; $categories = get_the_category_list( ', ', '', $post->ID ); return '<div id="cats" class="catting">' . $categories . '</div>'; } add_shortcode("cats", "catting"); ``` It shows the categories of a post listed simply and I managed to apply some custom styles on it in order to show it as buttons, but the style is being applied to the shortcode as a whole instead of affecting the categories separate and individually. I am trying to use `foreach` and to change the commas into a blank space between them, but, every time I try something, it breaks the code or it does not change anything at all. I would like to know the way to apply the style in each category separately and I thank you very much in advance for the help.
I've modified your code to reflect the `wp_list_categories()` function reference as suggested by @Usce. This snippet will create an unordered list, remove the "Categories" list title, and add the `li` class with individual category ID so you can target each link in the list. `function catting ($atts, $content = null) { echo '<div id="cats" class="catting">' . wp_list_categories('title_li=','current_category') . '</div>'; } add_shortcode("cats", "catting");` Here's some CSS to remove the bullets and margin so it essentially behaves just as your original code but with `li` wrapping your anchors. The CSS will break the list we've created into a horizontal line. Just remember to modify your CSS to further customize the outcome i.e. adding styles for buttons. `#cats.catting ul { display: inline; } #cats.catting ul li.cat-item { list-style: none; margin: 0px 10px; }` I hope this answers your question.
225,281
<p>After migrating my wordpress site users <strong>who are not Admins</strong> are redirected to the site's <strong>homepage after login</strong>. On the old site they were redirected on wp-admin. The Administrator is redirected to wp_admin as it should.</p> <p>I want the users to be redirected to <code>wp-admin</code> after login.</p> <p>I changed siteurl from the database (<code>wp_options</code>), also added this filter in my <code>functions.php</code>:</p> <pre><code>function my_login_redirect( $redirect_to, $request, $user ) { return admin_url(); } add_filter( 'login_redirect', 'my_login_redirect', 10, 3 ); </code></pre> <p>Any help please? Thank you and Happy Easter!</p>
[ { "answer_id": 225331, "author": "Hello Lili", "author_id": 91684, "author_profile": "https://wordpress.stackexchange.com/users/91684", "pm_score": 4, "selected": true, "text": "<p>Yeeey, I figured it out! Actually my theme had a redirect like this one in <code>functions.php</code>:</p>\n\n<pre><code>// Block Access to /wp-admin for non admins.\nfunction custom_blockusers_init() {\n if ( is_user_logged_in() &amp;&amp; is_admin() &amp;&amp; !current_user_can( 'administrator' ) ) {\n wp_redirect( home_url() );\n exit;\n }\n}\nadd_action( 'init', 'custom_blockusers_init' ); // Hook into 'init'\n</code></pre>\n\n<p>All you have to do is add your own role capability, for example: <code>!current_user_can( 'manage-reports' )</code></p>\n\n<p><a href=\"https://stackoverflow.com/questions/9408334/wordpress-admin-ajax-results-in-error-302-redirect\">This</a> helped me a lot.</p>\n" }, { "answer_id": 289022, "author": "Patrick Ogbuitepu", "author_id": 133560, "author_profile": "https://wordpress.stackexchange.com/users/133560", "pm_score": -1, "selected": false, "text": "<p>LAST RESORT THAT WORKS\nYou can temporarily disable redirection from the wp-login.php file and then delete all newly installed or updated plugins.</p>\n\n<ol>\n<li>Disable redirection by opening the file wp-login.php </li>\n</ol>\n\n<p>2.Scroll down to the line where you have the code \"do_action( \"login_form_{$action}\" );\"\nMine was around line 461</p>\n\n<ol start=\"3\">\n<li><p>Comment out that line of code to disable redirection</p></li>\n<li><p>Save the file. You will now be able to login using <a href=\"http://www.example.com/wp-login.php\" rel=\"nofollow noreferrer\">http://www.example.com/wp-login.php</a></p></li>\n<li><p>Disable or delete all recently installed plugins especially plugins that manage access control functionalities</p></li>\n<li><p>Clear your cookies and cache</p></li>\n</ol>\n" }, { "answer_id": 306665, "author": "Byeongin Yoon", "author_id": 136439, "author_profile": "https://wordpress.stackexchange.com/users/136439", "pm_score": 2, "selected": false, "text": "<p>@Hello Lili is right. But, we should check DOING_AJAX also!</p>\n\n<pre><code>// Block Access to /wp-admin for non admins.\nfunction custom_blockusers_init() {\n if ( is_user_logged_in() &amp;&amp; is_admin() &amp;&amp; !current_user_can( 'administrator' ) &amp;&amp; (defined( 'DOING_AJAX' ) &amp;&amp; !DOING_AJAX) ) ) {\n wp_redirect( home_url() );\n exit;\n }\n}\nadd_action( 'init', 'custom_blockusers_init' ); // Hook into 'init'\n</code></pre>\n" }, { "answer_id": 327098, "author": "user3408779", "author_id": 151814, "author_profile": "https://wordpress.stackexchange.com/users/151814", "pm_score": 0, "selected": false, "text": "<p>The below code is working like expected. This code restricts non admin users to access wp-admin or profile page.</p>\n\n<pre><code>add_action( 'admin_init', 'redirect_non_admin_users' );\n/**\n * Redirect non-admin users to home page\n *\n * This function is attached to the 'admin_init' action hook.\n */\nfunction redirect_non_admin_users() {\n if ( ! current_user_can( 'manage_options' ) &amp;&amp; '/wp-admin/admin-ajax.php' != $_SERVER['PHP_SELF'] ) {\n wp_redirect( home_url() );\n exit;\n }\n}\n</code></pre>\n" } ]
2016/04/30
[ "https://wordpress.stackexchange.com/questions/225281", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91684/" ]
After migrating my wordpress site users **who are not Admins** are redirected to the site's **homepage after login**. On the old site they were redirected on wp-admin. The Administrator is redirected to wp\_admin as it should. I want the users to be redirected to `wp-admin` after login. I changed siteurl from the database (`wp_options`), also added this filter in my `functions.php`: ``` function my_login_redirect( $redirect_to, $request, $user ) { return admin_url(); } add_filter( 'login_redirect', 'my_login_redirect', 10, 3 ); ``` Any help please? Thank you and Happy Easter!
Yeeey, I figured it out! Actually my theme had a redirect like this one in `functions.php`: ``` // Block Access to /wp-admin for non admins. function custom_blockusers_init() { if ( is_user_logged_in() && is_admin() && !current_user_can( 'administrator' ) ) { wp_redirect( home_url() ); exit; } } add_action( 'init', 'custom_blockusers_init' ); // Hook into 'init' ``` All you have to do is add your own role capability, for example: `!current_user_can( 'manage-reports' )` [This](https://stackoverflow.com/questions/9408334/wordpress-admin-ajax-results-in-error-302-redirect) helped me a lot.